//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Sim/Fitting/FitPrintService.cpp
//! @brief     Defines class FitPrintService.
//!
//! @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/FitPrintService.h"
#include "Base/Util/StringUtil.h"
#include "Fit/Minimizer/MinimizerResult.h"
#include "Sim/Fitting/FitObjective.h"
#include "Sim/Fitting/IterationInfo.h"
#include <iomanip>
#include <iostream>
#include <sstream>

void FitPrintService::print(const FitObjective& objective)
{
    std::ostringstream ostr;

    if (objective.isFirstIteration()) {
        m_run_time.start();
        m_last_call_time.start();
    }

    ostr << iterationHeaderString(objective);
    ostr << parameterString(objective);

    if (objective.isCompleted())
        ostr << fitResultString(objective);

    std::cout << ostr.str() << "\n";
}

std::string FitPrintService::iterationHeaderString(const FitObjective& objective)
{
    std::ostringstream result;

    m_last_call_time.stop();
    result << "Fit iteration " << objective.iterationInfo().iterationCount() << " Chi2 "
           << std::scientific << std::setprecision(8) << objective.iterationInfo().chi2() << " dt "
           << m_last_call_time.runTime() << "\n";
    m_last_call_time.start();

    return result.str();
}

std::string FitPrintService::parameterString(const FitObjective& objective)
{
    std::ostringstream result;

    result << "P";
    for (const auto& par : objective.iterationInfo().parameters())
        result << " " << std::scientific << std::setprecision(6) << par.value();
    result << "\n";

    return result.str();
}

std::string FitPrintService::fitResultString(const FitObjective& objective)
{
    std::ostringstream result;

    m_run_time.stop();

    result << "This was the last iteration." << std::endl;
    result << "Total time spend: " << std::fixed << std::setprecision(2) << m_run_time.runTime()
           << " sec."
           << "\n\n";

    result << objective.minimizerResult().toString();
    return result.str();
}
