//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/FitControl/FitObjectiveBuilder.cpp
//! @brief     Implements class FitObjectiveBuilder.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "GUI/View/FitControl/FitObjectiveBuilder.h"
#include "Base/Util/Assert.h"
#include "Device/Data/Datafield.h"
#include "Fit/Kernel/Minimizer.h"
#include "Fit/Minimizer/IMinimizer.h"
#include "GUI/Model/Data/DataItem.h"
#include "GUI/Model/File/DatafileItem.h"
#include "GUI/Model/Job/JobItem.h"
#include "GUI/Model/Mini/MinimizerItems.h"
#include "GUI/Model/ToCore/SimulationToCore.h"
#include "GUI/Model/Tune/FitParameterContainerItem.h"
#include "GUI/Model/Tune/FitSuiteItem.h"
#include "GUI/View/FitControl/GUIFitObserver.h"
#include "Sim/Fitting/FitObjective.h"
#include "Sim/Fitting/ObjectiveMetric.h"
#include "Sim/Simulation/ISimulation.h"

FitObjectiveBuilder::FitObjectiveBuilder(JobItem* jobItem)
    : m_job_item(jobItem)
{
    ASSERT(m_job_item);
    ASSERT(m_job_item->fitSuiteItem());
}

FitObjectiveBuilder::~FitObjectiveBuilder() = default;

void FitObjectiveBuilder::runFit()
{
    m_fit_objective = createFitObjective();
    m_fit_objective->setObjectiveMetric(
        m_job_item->fitSuiteItem()->minimizerContainerItem()->createMetric());

    if (m_observer) {
        fit_observer_t plot_observer = [&](const FitObjective& obj) { m_observer->update(&obj); };
        m_fit_objective->initPlot(1, std::move(plot_observer));
    }

    auto minimizer_impl = createMinimizer();
    const bool requires_residuals = minimizer_impl->requiresResiduals();

    mumufit::Minimizer minimizer;
    minimizer.setMinimizer(minimizer_impl.release());

    auto result = requires_residuals ? minimizer.minimize(
                                           [&](const mumufit::Parameters& params) {
                                               return m_fit_objective->evaluate_residuals(params);
                                           },
                                           createParameters())
                                     : minimizer.minimize(
                                           [&](const mumufit::Parameters& params) {
                                               return m_fit_objective->evaluate(params);
                                           },
                                           createParameters());
    m_fit_objective->finalize(result);
}

std::unique_ptr<FitObjective> FitObjectiveBuilder::createFitObjective() const
{
    auto result = std::make_unique<FitObjective>();

    simulation_builder_t builder = [&](const mumufit::Parameters& params) {
        return buildSimulation(params);
    };

    const auto* dfile_item = m_job_item->dfileItem();
    ASSERT(dfile_item);

    const DataItem* intensity_item = dfile_item->dataItem();
    ASSERT(intensity_item);
    ASSERT(intensity_item->c_field());

    std::unique_ptr<Datafield> data(intensity_item->c_field()->clone());

    result->addFitPair(builder, *data, 1.0);

    return result;
}

std::unique_ptr<IMinimizer> FitObjectiveBuilder::createMinimizer() const
{
    return m_job_item->fitSuiteItem()->minimizerContainerItem()->createMinimizer();
}

mumufit::Parameters FitObjectiveBuilder::createParameters() const
{
    return m_job_item->fitSuiteItem()->fitParameterContainerItem()->createParameters();
}

void FitObjectiveBuilder::attachObserver(std::shared_ptr<GUIFitObserver> observer)
{
    m_observer = observer;
}

void FitObjectiveBuilder::interruptFitting()
{
    m_fit_objective->interruptFitting();
}

std::unique_ptr<ISimulation>
FitObjectiveBuilder::buildSimulation(const mumufit::Parameters& params) const
{
    static std::mutex build_simulation_mutex;
    std::unique_lock<std::mutex> lock(build_simulation_mutex);

    update_fit_parameters(params);
    return GUI::ToCore::itemsToSimulation(m_job_item->sampleItem(), m_job_item->instrumentItem(),
                                          m_job_item->simulationOptionsItem());
}

void FitObjectiveBuilder::update_fit_parameters(const mumufit::Parameters& params) const
{
    auto* fitParContainer = m_job_item->fitSuiteItem()->fitParameterContainerItem();
    fitParContainer->setValuesInParameterContainer(params.values(),
                                                   m_job_item->parameterContainerItem());
}
