//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Sim/Fitting/FitStatus.cpp
//! @brief     Implements class FitStatus.
//!
//! @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 "Sim/Fitting/FitStatus.h"
#include "Fit/Minimizer/MinimizerResult.h"
#include "Sim/Fitting/FitPrintService.h"
#include <memory>
#include <stdexcept>

FitStatus::FitStatus(const FitObjective* fit_objective)
    : m_code(IDLE)
    , m_fit_objective(fit_objective)
{
}

FitStatus::~FitStatus() = default;

void FitStatus::setInterrupted()
{
    m_code = INTERRUPTED;
}

bool FitStatus::isInterrupted() const
{
    return m_code == INTERRUPTED;
}

bool FitStatus::isCompleted() const
{
    return m_code == COMPLETED;
}

void FitStatus::update(const mumufit::Parameters& params, double chi2)
{
    if (!isInterrupted())
        m_code = RUNNING;

    m_iteration_info.update(params, chi2);

    m_observers.notify(*m_fit_objective);
}

void FitStatus::initPrint(int every_nth)
{
    m_print_service = std::make_unique<FitPrintService>();

    FitObserver<FitObjective>::observer_t callback = [&](const FitObjective& objective) {
        m_print_service->print(objective);
    };

    addObserver(every_nth, std::move(callback));
}

void FitStatus::addObserver(int every_nth, fit_observer_t&& observer)
{
    m_observers.addObserver(every_nth, std::move(observer));
}
mumufit::MinimizerResult FitStatus::minimizerResult() const
{
    if (!m_minimizer_result)
        throw std::runtime_error("FitStatus::minimizerResult -> Minimizer result wasn't set. "
                                 "Make sure that FitObjective::finalize() was called.");

    return {*m_minimizer_result};
}

void FitStatus::finalize(const mumufit::MinimizerResult& result)
{
    m_minimizer_result = std::make_unique<mumufit::MinimizerResult>(result);
    m_code = COMPLETED;
    m_observers.notify_all(*m_fit_objective);
}
