//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
void RicExportToLasFileFeature::onActionTriggered(bool isChecked)
{
    this->disableModelChangeContribution();

    if (RicWellLogPlotCurveFeatureImpl::parentWellAllocationPlot()) return;

    std::vector<RimWellLogCurve*> curves = RicWellLogPlotCurveFeatureImpl::selectedWellLogCurves();
    if (curves.size() == 0) return;

    QString defaultDir = RiaApplication::instance()->lastUsedDialogDirectoryWithFallbackToProjectFolder("WELL_LOGS_DIR");

    RigLasFileExporter lasExporter(curves);
    RicExportToLasFileResampleUi featureUi;
    featureUi.exportFolder = defaultDir;

    {
        std::vector<QString> wellNames;
        std::vector<double> rkbDiffs;
        lasExporter.wellPathsAndRkbDiff(&wellNames, &rkbDiffs);
        featureUi.setRkbDiffs(wellNames, rkbDiffs);
    }
    
    caf::PdmUiPropertyViewDialog propertyDialog(nullptr, &featureUi, "Export Curve Data to LAS file(s)", "", QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    RicExportFeatureImpl::configureForExport(propertyDialog.dialogButtonBox());
    propertyDialog.resize(QSize(400, 330));
    
    if (propertyDialog.exec() == QDialog::Accepted &&
        !featureUi.exportFolder().isEmpty())
    {
        if (featureUi.activateResample)
        {
            lasExporter.setResamplingInterval(featureUi.resampleInterval());
        }

        if (featureUi.exportTvdrkb)
        {
            std::vector<QString> wellNames;
            std::vector<double> rkbDiffs;
            lasExporter.wellPathsAndRkbDiff(&wellNames, &rkbDiffs);

            std::vector<double> userDefRkbDiff;
            featureUi.tvdrkbDiffForWellPaths(&userDefRkbDiff);
            lasExporter.setRkbDiffs(wellNames, userDefRkbDiff);
        }

        lasExporter.writeToFolder(featureUi.exportFolder());

        // Remember the path to next time
        RiaApplication::instance()->setLastUsedDialogDirectory("WELL_LOGS_DIR", featureUi.exportFolder());
    }
}
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
void RicSaveEclipseResultAsInputPropertyExec::redo()
{
    CVF_ASSERT(m_cellColors);

    if (!m_cellColors->reservoirView()) return;
    if (!m_cellColors->reservoirView()->eclipseCase()) return;
    if (!m_cellColors->reservoirView()->eclipseCase()->reservoirData()) return;

    RimBinaryExportSettings exportSettings;
    exportSettings.eclipseKeyword = m_cellColors->resultVariable();
    {
        QString projectFolder;

        RiaApplication* app = RiaApplication::instance();
        QString projectFileName = app->currentProjectFileName();
        if (!projectFileName.isEmpty())
        {   
            QFileInfo fi(projectFileName);
            projectFolder = fi.absolutePath();
        }
        else
        {
            projectFolder = m_cellColors->reservoirView()->eclipseCase()->locationOnDisc();
        }

        QString outputFileName = projectFolder + "/" + m_cellColors->resultVariable();

        exportSettings.fileName = outputFileName;
    }

    caf::PdmUiPropertyViewDialog propertyDialog(RiuMainWindow::instance(), &exportSettings, "Export Binary Eclipse Data to Text File", "");
    if (propertyDialog.exec() == QDialog::Accepted)
    {
        size_t timeStep = m_cellColors->reservoirView()->currentTimeStep();
        RifReaderInterface::PorosityModelResultType porosityModel = RigCaseCellResultsData::convertFromProjectModelPorosityModel(m_cellColors->porosityModel());

        bool isOk = RifEclipseInputFileTools::writeBinaryResultToTextFile(exportSettings.fileName, m_cellColors->reservoirView()->eclipseCase()->reservoirData(), porosityModel, timeStep, m_cellColors->resultVariable(), exportSettings.eclipseKeyword, exportSettings.undefinedValue);
        if (!isOk)
        {
            QMessageBox::critical(NULL, "File export", "Failed to exported current result to " + exportSettings.fileName);
        }
    }
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicCreateSaturationPressurePlotsFeature::onActionTriggered(bool isChecked)
{
    RimProject* project = RiaApplication::instance()->project();

    RimSaturationPressurePlotCollection* collection = project->mainPlotCollection()->saturationPressurePlotCollection();

    std::vector<RimEclipseResultCase*> eclipseCases;
    {
        RiaApplication*       app = RiaApplication::instance();
        std::vector<RimCase*> cases;
        app->project()->allCases(cases);
        for (auto* rimCase : cases)
        {
            auto erc = dynamic_cast<RimEclipseResultCase*>(rimCase);
            if (erc)
            {
                eclipseCases.push_back(erc);
            }
        }
    }

    RimEclipseResultCase* eclipseResultCase = nullptr;

    if (!eclipseCases.empty())
    {
        if (eclipseCases.size() == 1)
        {
            eclipseResultCase = eclipseCases[0];
        }
        else
        {
            RicSaturationPressureUi saturationPressureUi;
            saturationPressureUi.setSelectedCase(eclipseCases[0]);

            RiuPlotMainWindow* plotwindow = RiaApplication::instance()->mainPlotWindow();

            caf::PdmUiPropertyViewDialog propertyDialog(
                plotwindow, &saturationPressureUi, "Select Case to create Pressure Saturation plots", "");

            if (propertyDialog.exec() == QDialog::Accepted)
            {
                eclipseResultCase = dynamic_cast<RimEclipseResultCase*>(saturationPressureUi.selectedCase());
            }
        }
    }

    caf::PdmObject* objectToSelect = nullptr;

    std::vector<RimSaturationPressurePlot*> plots = createPlots(eclipseResultCase);
    if (plots.empty())
    {
        QString text = "No plots generated.\n\n";
        text += "Data required to generate saturation/pressure plots:\n";
        text += " - EQLNUM property defining at least one region\n";
        text += " - Dynamic properties PRESSURE, PBUB and PDEW\n\n";
        text += "Make sure to add 'PBPD' to the RPTRST keyword in the SOLUTION selection. ";
        text += "If this is a two phase run (Oil/water or Gas/Water) or if both VAPOIL ";
        text += "and DISGAS are disabled, saturation pressure are not valid.";

        QMessageBox::warning(nullptr, "Saturation Pressure Plots", text);

        RiaLogging::warning(text);
    }
    else
    {
        objectToSelect = plots.front();
    }

    collection->updateAllRequiredEditors();
    RiaApplication::instance()->getOrCreateAndShowMainPlotWindow();

    if (objectToSelect)
    {
        RiuPlotMainWindowTools::selectAsCurrentItem(objectToSelect);
    }
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicWellPathExportCompletionDataFeature::prepareExportSettingsAndExportCompletions(
    const QString&                        dialogTitle,
    const std::vector<RimWellPath*>&      wellPaths,
    const std::vector<RimSimWellInView*>& simWells)
{
    RiaApplication* app        = RiaApplication::instance();
    RimProject*     project    = app->project();
    QString         defaultDir = RiaApplication::instance()->lastUsedDialogDirectoryWithFallbackToProjectFolder("COMPLETIONS");

    RicExportCompletionDataSettingsUi* exportSettings = project->dialogData()->exportCompletionData();

    if (wellPaths.empty())
    {
        exportSettings->showForSimWells();
    }
    else
    {
        exportSettings->showForWellPath();
    }

    if (!exportSettings->caseToApply())
    {
        std::vector<RimCase*> cases;
        app->project()->allCases(cases);
        for (auto c : cases)
        {
            RimEclipseCase* eclipseCase = dynamic_cast<RimEclipseCase*>(c);
            if (eclipseCase != nullptr)
            {
                exportSettings->caseToApply = eclipseCase;
                break;
            }
        }
    }

    if (exportSettings->folder().isEmpty()) exportSettings->folder = defaultDir;

    std::vector<RimSimWellFracture*>       simWellFractures;
    std::vector<RimWellPathFracture*>      wellPathFractures;
    std::vector<RimFishbonesMultipleSubs*> wellPathFishbones;
    std::vector<RimPerforationInterval*>   wellPathPerforations;

    for (auto s : simWells)
    {
        s->descendantsIncludingThisOfType(simWellFractures);
    }

    for (auto w : wellPaths)
    {
        w->descendantsIncludingThisOfType(wellPathFractures);
        w->descendantsIncludingThisOfType(wellPathFishbones);
        w->descendantsIncludingThisOfType(wellPathPerforations);
    }

    if ((!simWellFractures.empty()) || (!wellPathFractures.empty()))
    {
        exportSettings->showFractureInUi(true);
    }
    else
    {
        exportSettings->showFractureInUi(false);
    }

    if (!wellPathFishbones.empty())
    {
        exportSettings->showFishbonesInUi(true);
    }
    else
    {
        exportSettings->showFishbonesInUi(false);
    }

    if (!wellPathPerforations.empty())
    {
        exportSettings->showPerforationsInUi(true);

        std::vector<const RimWellPathValve*> perforationValves;
        for (const auto& perf : wellPathPerforations)
        {
            perf->descendantsIncludingThisOfType(perforationValves);
        }

        if (!perforationValves.empty())
        {
            exportSettings->enableIncludeMsw();
        }
    }
    else
    {
        exportSettings->showPerforationsInUi(false);
    }

    caf::PdmUiPropertyViewDialog propertyDialog(Riu3DMainWindowTools::mainWindowWidget(), exportSettings, dialogTitle, "");
    RicExportFeatureImpl::configureForExport(propertyDialog.dialogButtonBox());

    if (propertyDialog.exec() == QDialog::Accepted)
    {
        RiaApplication::instance()->setLastUsedDialogDirectory("COMPLETIONS", exportSettings->folder);

        RicWellPathExportCompletionDataFeatureImpl::exportCompletions(wellPaths, simWells, *exportSettings);
    }
}