//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimEclipseInputCaseOpm::updateFilePathsFromProjectPath(const QString& newProjectPath, const QString& oldProjectPath)
{
    bool foundFile = false;
    std::vector<QString> searchedPaths;

    m_gridFileName = RimTools::relocateFile(m_gridFileName(), newProjectPath, oldProjectPath, &foundFile, &searchedPaths);

    for (size_t i = 0; i < m_additionalFileNames().size(); i++)
    {
        m_additionalFileNames.v()[i] = RimTools::relocateFile(m_additionalFileNames()[i], newProjectPath, oldProjectPath, &foundFile, &searchedPaths);
    }
}
//--------------------------------------------------------------------------------------------------
/// Open the supplied file set. If no grid data has been read, it will first find the possible 
/// grid data among the files then read all supported properties from the files matching the grid
//--------------------------------------------------------------------------------------------------
void RimEclipseInputCase::openDataFileSet(const QStringList& fileNames)
{
    if (fileNames.contains(RimDefines::mockModelBasicInputCase()))
    {
        cvf::ref<RifReaderInterface> readerInterface = this->createMockModel(fileNames[0]);
        results(RifReaderInterface::MATRIX_RESULTS)->setReaderInterface(readerInterface.p());
        results(RifReaderInterface::FRACTURE_RESULTS)->setReaderInterface(readerInterface.p());

        reservoirData()->activeCellInfo(RifReaderInterface::MATRIX_RESULTS)->computeDerivedData();
        reservoirData()->activeCellInfo(RifReaderInterface::FRACTURE_RESULTS)->computeDerivedData();
        
        QFileInfo gridFileName(fileNames[0]);
        QString caseName = gridFileName.completeBaseName();
        this->caseUserDescription = caseName;
        
        computeCachedData();

        return;
    }

    if (this->reservoirData() == NULL) 
    {
        this->setReservoirData(new RigCaseData);
    }

    // First find and read the grid data 
    if (this->reservoirData()->mainGrid()->gridPointDimensions() == cvf::Vec3st(0,0,0))
    {
        RiaPreferences* prefs = RiaApplication::instance()->preferences();

         for (int i = 0; i < fileNames.size(); i++)
         {
             if (RifEclipseInputFileTools::openGridFile(fileNames[i], this->reservoirData(), prefs->readerSettings->importFaults()))
             {
                 m_gridFileName = fileNames[i];

                 QFileInfo gridFileName(fileNames[i]);
                 QString caseName = gridFileName.completeBaseName();

                 this->caseUserDescription = caseName;

                 this->reservoirData()->mainGrid()->setFlipAxis(flipXAxis, flipYAxis);

                 computeCachedData();

                 break;
             }
         }
    }

    if (this->reservoirData()->mainGrid()->gridPointDimensions() == cvf::Vec3st(0,0,0))
    {
        return ; // No grid present
    }

    // Then read the properties possibly in the grid file
    QStringList filesToRead;
    for (int i = 0; i < fileNames.size(); i++)
    {
        size_t j;
        bool exist = false;
        for (j = 0; j < m_additionalFileNames().size(); j++)
        {
            if (m_additionalFileNames()[j] == fileNames[i])
            {
                exist = true;
            }
        }

        if (!exist)
        {
            filesToRead.push_back(fileNames[i]);
        }
    }

    for (int i = 0; i < filesToRead.size(); i++)
    {
        QString propertyFileName = filesToRead[i];
        std::map<QString, QString> readProperties = RifEclipseInputFileTools::readProperties(propertyFileName, this->reservoirData());

        std::map<QString, QString>::iterator it;
        for (it = readProperties.begin(); it != readProperties.end(); ++it)
        {
            RimEclipseInputProperty* inputProperty = new RimEclipseInputProperty;
            inputProperty->resultName = it->first;
            inputProperty->eclipseKeyword = it->second;
            inputProperty->fileName = propertyFileName;
            inputProperty->resolvedState = RimEclipseInputProperty::RESOLVED;
            m_inputPropertyCollection->inputProperties.push_back(inputProperty);
        }

        if (propertyFileName != m_gridFileName)
        {
            m_additionalFileNames.v().push_back(propertyFileName);
        }
    }
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimEclipseInputCaseOpm::loadAndSyncronizeInputProperties()
{
    // Make sure we actually have reservoir data

    CVF_ASSERT(this->reservoirData());
    CVF_ASSERT(this->reservoirData()->mainGrid()->gridPointDimensions() != cvf::Vec3st(0, 0, 0));

    // Then read the properties from all the files referenced by the InputReservoir

    for (QString filename : m_additionalFileNames())
    {
        QFileInfo fileNameInfo(filename);
        bool isExistingFile = fileNameInfo.exists();

        // Find the input property objects referring to the file

        std::vector<RimEclipseInputProperty*> ipsUsingThisFile = this->m_inputPropertyCollection()->findInputProperties(filename);

        if (!isExistingFile)
        {
            for (auto inputProperty : ipsUsingThisFile)
            {
                inputProperty->resolvedState = RimEclipseInputProperty::FILE_MISSING;
            }
        }
        else
        {
            RifReaderOpmParserPropertyReader propertyReader(filename);
            std::set<std::string> fileKeywordSet = propertyReader.keywords();

            for (auto inputProperty : ipsUsingThisFile)
            {
                QString kw = inputProperty->eclipseKeyword();
                inputProperty->resolvedState = RimEclipseInputProperty::KEYWORD_NOT_IN_FILE;
                if (fileKeywordSet.count(kw.toStdString()))
                {
                    if (propertyReader.copyPropertyToCaseData(kw.toStdString(), this->reservoirData(), inputProperty->resultName))
                    {
                        inputProperty->resolvedState = RimEclipseInputProperty::RESOLVED;
                    }
                }
                fileKeywordSet.erase(kw.toStdString());
            }

            if (!fileKeywordSet.empty())
            {
                std::vector<std::string> knownKeywords = RifReaderOpmParserInput::knownPropertyKeywords();
                for (auto knownKeyword : knownKeywords)
                {
                    if (fileKeywordSet.count(knownKeyword) > 0)
                    {
                        QString qtKnownKeyword = QString::fromStdString(knownKeyword);
                        QString resultName = this->reservoirData()->results(RifReaderInterface::MATRIX_RESULTS)->makeResultNameUnique(qtKnownKeyword);
                        if (propertyReader.copyPropertyToCaseData(knownKeyword, this->reservoirData(), resultName))
                        {
                            RimEclipseInputProperty* inputProperty = new RimEclipseInputProperty;
                            inputProperty->resultName = resultName;
                            inputProperty->eclipseKeyword = qtKnownKeyword;
                            inputProperty->fileName = filename;
                            inputProperty->resolvedState = RimEclipseInputProperty::RESOLVED;
                            m_inputPropertyCollection->inputProperties.push_back(inputProperty);
                        }
                    }
                }
            }
        }
    }

    for(auto inputProperty : m_inputPropertyCollection->inputProperties())
    {
        if (inputProperty->resolvedState() == RimEclipseInputProperty::UNKNOWN)
        {
            inputProperty->resolvedState = RimEclipseInputProperty::FILE_MISSING;
        }
    }
}
//--------------------------------------------------------------------------------------------------
/// Open the supplied file set. If no grid data has been read, it will first find the possible 
/// grid data among the files then read all supported properties from the files matching the grid
//--------------------------------------------------------------------------------------------------
void RimInputReservoir::openDataFileSet(const QStringList& filenames)
{
    if (caseName().contains("Input Mock Debug Model"))
    {
        cvf::ref<RifReaderInterface> readerInterface = this->createMockModel(this->caseName());
        m_rigReservoir->mainGrid()->results(RifReaderInterface::MATRIX_RESULTS)->setReaderInterface(readerInterface.p());
        m_rigReservoir->mainGrid()->results(RifReaderInterface::FRACTURE_RESULTS)->setReaderInterface(readerInterface.p());

        size_t matrixActiveCellCount = 0;
        size_t fractureActiveCellCount = 0;

        for (size_t cellIdx = 0; cellIdx < m_rigReservoir->mainGrid()->cells().size(); cellIdx++)
        {
            const RigCell& cell = m_rigReservoir->mainGrid()->cells()[cellIdx];

            if (cell.isActiveInMatrixModel())
            {
                matrixActiveCellCount++;
            }
            if (cell.isActiveInFractureModel())
            {
                fractureActiveCellCount++;
            }

        }

        m_rigReservoir->mainGrid()->setGlobalMatrixModelActiveCellCount(matrixActiveCellCount);
        m_rigReservoir->mainGrid()->setGlobalFractureModelActiveCellCount(fractureActiveCellCount);

        return;
    }

    if (m_rigReservoir.isNull()) 
    {
        RigReservoir* reservoir = new RigReservoir;
        m_rigReservoir = reservoir;
    }

    // First find and read the grid data 
    if (this->reservoirData()->mainGrid()->gridPointDimensions() == cvf::Vec3st(0,0,0))
    {
         for (int i = 0; i < filenames.size(); i++)
         {
             if (RifEclipseInputFileTools::openGridFile(filenames[i], this->reservoirData()))
             {
                 m_gridFileName = filenames[i];

                 m_rigReservoir->computeFaults();
                 m_rigReservoir->mainGrid()->computeCachedData();

                 break;
             }
         }
    }

    if (this->reservoirData()->mainGrid()->gridPointDimensions() == cvf::Vec3st(0,0,0))
    {
        return ; // No grid present
    }

    // Then read the properties possibly in the grid file
    QStringList filesToRead;
    for (int i = 0; i < filenames.size(); i++)
    {
        size_t j;
        bool exist = false;
        for (j = 0; j < m_additionalFileNames().size(); j++)
        {
            if (m_additionalFileNames()[j] == filenames[i])
            {
                exist = true;
            }
        }

        if (!exist)
        {
            filesToRead.push_back(filenames[i]);
        }
    }

    for (int i = 0; i < filesToRead.size(); i++)
    {
        QString propertyFileName = filesToRead[i];
        std::map<QString, QString> readProperties = RifEclipseInputFileTools::readProperties(propertyFileName, this->reservoirData());

        std::map<QString, QString>::iterator it;
        for (it = readProperties.begin(); it != readProperties.end(); ++it)
        {
            RimInputProperty* inputProperty = new RimInputProperty;
            inputProperty->resultName = it->first;
            inputProperty->eclipseKeyword = it->second;
            inputProperty->fileName = propertyFileName;
            inputProperty->resolvedState = RimInputProperty::RESOLVED;
            m_inputPropertyCollection->inputProperties.push_back(inputProperty);
        }

        if (propertyFileName != m_gridFileName)
        {
            m_additionalFileNames.v().push_back(propertyFileName);
        }
    }
}