//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
void RimEclipseCellColors::updateLegendData(RimEclipseCase*         rimEclipseCase, 
                                            int                     currentTimeStep,
                                            RimRegularLegendConfig* legendConfig, 
                                            RimTernaryLegendConfig* ternaryLegendConfig)
{
    if (!legendConfig) legendConfig = this->legendConfig();
    if (!ternaryLegendConfig) ternaryLegendConfig = this->m_ternaryLegendConfig();

    if ( this->hasResult() )
    {
        if ( this->isFlowDiagOrInjectionFlooding() )
        {
            CVF_ASSERT(currentTimeStep >= 0);

            double globalMin, globalMax;
            double globalPosClosestToZero, globalNegClosestToZero;
            RigFlowDiagResults* flowResultsData = this->flowDiagSolution()->flowDiagResults();
            RigFlowDiagResultAddress resAddr = this->flowDiagResAddress();

            flowResultsData->minMaxScalarValues(resAddr, currentTimeStep, &globalMin, &globalMax);
            flowResultsData->posNegClosestToZero(resAddr, currentTimeStep, &globalPosClosestToZero, &globalNegClosestToZero);

            double localMin, localMax;
            double localPosClosestToZero, localNegClosestToZero;
            if ( this->hasDynamicResult() )
            {
                flowResultsData->minMaxScalarValues(resAddr, currentTimeStep, &localMin, &localMax);
                flowResultsData->posNegClosestToZero(resAddr, currentTimeStep, &localPosClosestToZero, &localNegClosestToZero);
            }
            else
            {
                localMin = globalMin;
                localMax = globalMax;

                localPosClosestToZero = globalPosClosestToZero;
                localNegClosestToZero = globalNegClosestToZero;
            }

            CVF_ASSERT(legendConfig);

            legendConfig->disableAllTimeStepsRange(true);
            legendConfig->setClosestToZeroValues(globalPosClosestToZero, globalNegClosestToZero, 
                                                         localPosClosestToZero, localNegClosestToZero);
            legendConfig->setAutomaticRanges(globalMin, globalMax, localMin, localMax);

            if ( this->hasCategoryResult() && m_reservoirView)
            {
                std::set<std::tuple<QString, int, cvf::Color3ub>, TupleCompare > categories;
                //std::set<std::tuple<QString, int, cvf::Color3ub> > categories;

                std::vector<QString> tracerNames = this->flowDiagSolution()->tracerNames();
                int tracerIndex = 0;
                for ( const auto& tracerName : tracerNames )
                {
                    RimSimWellInView* well = m_reservoirView->wellCollection()->findWell(RimFlowDiagSolution::removeCrossFlowEnding(tracerName));
                    cvf::Color3ub color(cvf::Color3::GRAY);
                    if ( well ) color = cvf::Color3ub(well->wellPipeColor());

                    categories.insert(std::make_tuple(tracerName, tracerIndex, color));
                    ++tracerIndex;
                }

                std::vector<std::tuple<QString, int, cvf::Color3ub>> reverseCategories;
                for ( auto tupIt = categories.rbegin(); tupIt != categories.rend(); ++tupIt )
                {
                    reverseCategories.push_back(*tupIt);
                }

                legendConfig->setCategoryItems(reverseCategories);
            }
        }
        else
        {
            CVF_ASSERT(rimEclipseCase);
            if ( !rimEclipseCase ) return;

            RigEclipseCaseData* eclipseCase = rimEclipseCase->eclipseCaseData();
            CVF_ASSERT(eclipseCase);
            if ( !eclipseCase ) return;

            RigCaseCellResultsData* cellResultsData = eclipseCase->results(this->porosityModel());
            CVF_ASSERT(cellResultsData);

            double globalMin, globalMax;
            double globalPosClosestToZero, globalNegClosestToZero;

            cellResultsData->minMaxCellScalarValues(this->eclipseResultAddress(), globalMin, globalMax);
            cellResultsData->posNegClosestToZero(this->eclipseResultAddress(), globalPosClosestToZero, globalNegClosestToZero);

            double localMin, localMax;
            double localPosClosestToZero, localNegClosestToZero;
            if ( this->hasDynamicResult() && currentTimeStep >= 0)
            {
                cellResultsData->minMaxCellScalarValues(this->eclipseResultAddress(), currentTimeStep, localMin, localMax);
                cellResultsData->posNegClosestToZero(this->eclipseResultAddress(), currentTimeStep, localPosClosestToZero, localNegClosestToZero);
            }
            else
            {
                localMin = globalMin;
                localMax = globalMax;

                localPosClosestToZero = globalPosClosestToZero;
                localNegClosestToZero = globalNegClosestToZero;
            }

            CVF_ASSERT(legendConfig);

            legendConfig->disableAllTimeStepsRange(false);
            legendConfig->setClosestToZeroValues(globalPosClosestToZero, globalNegClosestToZero, localPosClosestToZero, localNegClosestToZero);
            legendConfig->setAutomaticRanges(globalMin, globalMax, localMin, localMax);

            if ( this->hasCategoryResult() )
            {
                if ( this->resultType() == RiaDefines::FORMATION_NAMES )
                {
                    const std::vector<QString>& fnVector = eclipseCase->activeFormationNames()->formationNames();
                    legendConfig->setNamedCategoriesInverse(fnVector);
                }
                else if ( this->resultType() == RiaDefines::DYNAMIC_NATIVE && this->resultVariable() == RiaDefines::completionTypeResultName() )
                {   
                    const std::vector<int>& visibleCategories = cellResultsData->uniqueCellScalarValues(this->eclipseResultAddress());

                    std::vector<RiaDefines::WellPathComponentType> supportedCompletionTypes =
                        { RiaDefines::WELL_PATH, RiaDefines::FISHBONES, RiaDefines::PERFORATION_INTERVAL, RiaDefines::FRACTURE };
                    
                    RiaColorTables::WellPathComponentColors colors = RiaColorTables::wellPathComponentColors();
                    
                    std::vector< std::tuple<QString, int, cvf::Color3ub> > categories;
                    for (auto completionType : supportedCompletionTypes)
                    {
                        if (std::find(visibleCategories.begin(), visibleCategories.end(), completionType) != visibleCategories.end())
                        {
                            QString categoryText = caf::AppEnum<RiaDefines::WellPathComponentType>::uiText(completionType);
                            categories.push_back(std::make_tuple(categoryText, completionType, colors[completionType]));
                        }
                    }

                    legendConfig->setCategoryItems(categories);
                }
                else
                {
                    legendConfig->setIntegerCategories(cellResultsData->uniqueCellScalarValues(this->eclipseResultAddress()));
                }
            }
        }
    }

    // Ternary legend update
    {
        CVF_ASSERT(rimEclipseCase);
        if ( !rimEclipseCase ) return;

        RigEclipseCaseData* eclipseCase = rimEclipseCase->eclipseCaseData();
        CVF_ASSERT(eclipseCase);
        if ( !eclipseCase ) return;


        RigCaseCellResultsData* cellResultsData = eclipseCase->results(this->porosityModel());

        size_t maxTimeStepCount = cellResultsData->maxTimeStepCount();
        if ( this->isTernarySaturationSelected() && maxTimeStepCount > 1 )
        {
            RigCaseCellResultsData* gridCellResults = this->currentGridCellResults();
            {
                RigEclipseResultAddress resAddr(RiaDefines::DYNAMIC_NATIVE, "SOIL");

                if ( gridCellResults->ensureKnownResultLoaded(resAddr) )
                {
                    double globalMin = 0.0;
                    double globalMax = 1.0;
                    double localMin = 0.0;
                    double localMax = 1.0;

                    cellResultsData->minMaxCellScalarValues(resAddr, globalMin, globalMax);
                    cellResultsData->minMaxCellScalarValues(resAddr, currentTimeStep, localMin, localMax);

                    ternaryLegendConfig->setAutomaticRanges(RimTernaryLegendConfig::TERNARY_SOIL_IDX, globalMin, globalMax, localMin, localMax);
                }
            }

            {
                RigEclipseResultAddress resAddr(RiaDefines::DYNAMIC_NATIVE, "SGAS");
                
                if ( gridCellResults->ensureKnownResultLoaded(resAddr) )
                {
                    double globalMin = 0.0;
                    double globalMax = 1.0;
                    double localMin = 0.0;
                    double localMax = 1.0;

                    cellResultsData->minMaxCellScalarValues(resAddr, globalMin, globalMax);
                    cellResultsData->minMaxCellScalarValues(resAddr, currentTimeStep, localMin, localMax);

                    ternaryLegendConfig->setAutomaticRanges(RimTernaryLegendConfig::TERNARY_SGAS_IDX, globalMin, globalMax, localMin, localMax);
                }
            }

            {
                RigEclipseResultAddress resAddr(RiaDefines::DYNAMIC_NATIVE, "SWAT");

                if ( gridCellResults->ensureKnownResultLoaded(resAddr) )
                {
                    double globalMin = 0.0;
                    double globalMax = 1.0;
                    double localMin = 0.0;
                    double localMax = 1.0;

                    cellResultsData->minMaxCellScalarValues(resAddr, globalMin, globalMax);
                    cellResultsData->minMaxCellScalarValues(resAddr, currentTimeStep, localMin, localMax);

                    ternaryLegendConfig->setAutomaticRanges(RimTernaryLegendConfig::TERNARY_SWAT_IDX, globalMin, globalMax, localMin, localMax);
                }
            }
        }
    }
}