//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
void RicfCreateMultipleFractures::execute()
{
    using TOOLS = RicfApplicationTools;

    RimProject* project = RiaApplication::instance()->project();
    RiuCreateMultipleFractionsUi* settings = project->dialogData()->multipleFractionsData();

    // Get case and fracture template
    auto gridCase = TOOLS::caseFromId(m_caseId);
    auto fractureTemplate = fractureTemplateFromId(m_templateId);
    std::vector<RimWellPath*> wellPaths;

    // Find well paths
    {
        QStringList wellsNotFound;
        wellPaths = TOOLS::wellPathsFromNames(TOOLS::toQStringList(m_wellPathNames), &wellsNotFound);
        if (!wellsNotFound.empty())
        {
            RiaLogging::error(QString("createMultipleFractures: These well paths were not found: ") + wellsNotFound.join(", "));
        }
    }

    if (!gridCase)
    {
        RiaLogging::error(QString("createMultipleFractures: Could not find case with ID %1").arg(m_caseId));
    }

    if (!fractureTemplate)
    {
        RiaLogging::error(QString("createMultipleFractures: Could not find fracture template with ID %1").arg(m_templateId));
    }

    if (gridCase && fractureTemplate && !wellPaths.empty() && validateArguments())
    {
        RicCreateMultipleFracturesOptionItemUi* options = new RicCreateMultipleFracturesOptionItemUi();
        caf::CmdFeatureManager*                 commandManager = caf::CmdFeatureManager::instance();
        auto feature = dynamic_cast<RicCreateMultipleFracturesFeature*>(commandManager->getCommandFeature("RicCreateMultipleFracturesFeature"));

        // Default layers
        int topLayer = m_topLayer;
        int baseLayer = m_baseLayer;
        if (feature && (topLayer < 0 || baseLayer < 0))
        {
            auto ijkRange = feature->ijkRangeForGrid(gridCase);
            if (topLayer < 0) topLayer = static_cast<int>(ijkRange.first.z());
            if (baseLayer < 0) baseLayer = static_cast<int>(ijkRange.second.z());
        }
        options->setValues(topLayer, baseLayer, fractureTemplate, m_spacing);

        settings->clearWellPaths();
        for (auto wellPath : wellPaths)
        {
            settings->addWellPath(wellPath);
        }

        settings->setValues(gridCase, m_minDistFromWellTd, m_maxFracturesPerWell);
        settings->clearOptions();
        settings->insertOptionItem(nullptr, options);


        if (feature)
        {
            if (m_action == MultipleFractures::APPEND_FRACTURES)    feature->appendFractures();
            if (m_action == MultipleFractures::REPLACE_FRACTURES)   feature->replaceFractures();
        }
    }
}
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
void RicfExportSimWellFractureCompletions::execute()
{
    RimProject* project = RiaApplication::instance()->project();
    RicExportCompletionDataSettingsUi* exportSettings = project->dialogData()->exportCompletionData();
    
    exportSettings->timeStep = m_timeStep;
    exportSettings->fileSplit = m_fileSplit;
    exportSettings->compdatExport = m_compdatExport;

    {
        bool foundCase = false;
        for (RimEclipseCase* c : RiaApplication::instance()->project()->activeOilField()->analysisModels->cases())
        {
            if (c->caseId() == m_caseId())
            {
                exportSettings->caseToApply = c;
                foundCase = true;
                break;
            }
        }
        if (!foundCase)
        {
            RiaLogging::error(QString("exportSimWellCompletions: Could not find case with ID %1").arg(m_caseId()));
            return;
        }
    }

    QString exportFolder = RicfCommandFileExecutor::instance()->getExportPath(RicfCommandFileExecutor::COMPLETIONS);
    if (exportFolder.isNull())
    {
        exportFolder = RiaApplication::instance()->createAbsolutePathFromProjectRelativePath("completions");
    }
    exportSettings->folder = exportFolder;

    std::vector<RimEclipseView*> views;
    for (Rim3dView* v : exportSettings->caseToApply->views())
    {
        RimEclipseView* eclipseView = dynamic_cast<RimEclipseView*>(v);
        if (eclipseView && eclipseView->name() == m_viewName())
        {
            views.push_back(eclipseView);
        }
    }
    if (views.empty())
    {
        RiaLogging::error(QString("exportSimWellCompletions: Could not find any views named \"%1\" in the case with ID %2").arg(m_viewName).arg(m_caseId()));
        return;
    }

    std::vector<RimSimWellInView*> simWells;
    if (m_simWellNames().empty())
    {
        for (RimEclipseView* view : views)
        {
            for (auto simWell : view->wellCollection()->wells)
            {
                if (simWell->showWell())
                {
                    simWells.push_back(simWell);
                }
            }
        }
    }
    else
    {
        for (const QString& wellPathName : m_simWellNames())
        {
            for (RimEclipseView* view : views)
            {
                RimSimWellInView* simWell = view->wellCollection()->findWell(wellPathName);
                if (simWell)
                {
                    simWells.push_back(simWell);
                }
                else
                {
                    RiaLogging::warning(QString("exportSimWellCompletions: Could not find well with name %1 in view \"%2\" on case with ID %2").arg(wellPathName).arg(m_viewName).arg(m_caseId()));
                }
            }
        }
    }

    std::vector<RimWellPath*> wellPaths;

    RicWellPathExportCompletionDataFeatureImpl::exportCompletions(wellPaths, simWells, *exportSettings);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
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);
    }
}