//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Tune/FitSuiteItem.cpp
//! @brief     Implements class FitSuiteItem.
//!
//! @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/Model/Tune/FitSuiteItem.h"
#include "GUI/Model/Mini/MinimizerItems.h"
#include "GUI/Model/Tune/FitParameterContainerItem.h"
#include "GUI/Model/Util/UtilXML.h"

namespace {
namespace Tag {

const QString UpdateInterval("UpdateInterval");
const QString IterationsCount("IterationsCount");
const QString Chi2("Chi2");

const QString MinimizerContainer("MinimizerContainer");
const QString FitParameterContainer("FitParameterContainer");

} // namespace Tag
} // namespace

FitSuiteItem::FitSuiteItem()
    : m_update_interval(10)
    , m_iter_count(0)
    , m_chi2(0.0)
    , m_fit_container(std::make_unique<FitParameterContainerItem>())
    , m_minimizer_container(std::make_unique<MinimizerContainerItem>())
{
    setObjectName("FitSuite");
}

FitSuiteItem::~FitSuiteItem() = default;

void FitSuiteItem::setUpdateInterval(int interval)
{
    m_update_interval = interval;
    emit updateIntervalChanged(interval);
}

void FitSuiteItem::setIterationCount(int count)
{
    m_iter_count = count;
    emit iterationCountChanged(count);
}

void FitSuiteItem::setChi2(const double chi2)
{
    m_chi2 = chi2;
}

void FitSuiteItem::writeTo(QXmlStreamWriter* w) const
{
    XML::writeTaggedValue(w, Tag::UpdateInterval, m_update_interval);
    XML::writeTaggedValue(w, Tag::IterationsCount, m_iter_count);
    XML::writeTaggedValue(w, Tag::Chi2, m_chi2);

    // minimizer container
    if (m_minimizer_container) {
        XML::writeTaggedElement(w, Tag::MinimizerContainer, *m_minimizer_container);
    }

    // fit parameter container
    if (m_fit_container) {
        XML::writeTaggedElement(w, Tag::FitParameterContainer, *m_fit_container);
    }
}

void FitSuiteItem::readFrom(QXmlStreamReader* r)
{
    while (r->readNextStartElement()) {
        QString tag = r->name().toString();
        if (tag == Tag::UpdateInterval)
            m_update_interval = XML::readTaggedInt(r, tag);
        else if (tag == Tag::IterationsCount)
            m_iter_count = XML::readTaggedInt(r, tag);
        else if (tag == Tag::Chi2)
            m_chi2 = XML::readTaggedDouble(r, tag);
        else if (tag == Tag::MinimizerContainer)
            XML::readTaggedElement(r, tag, *m_minimizer_container);
        else if (tag == Tag::FitParameterContainer)
            XML::readTaggedElement(r, tag, *m_fit_container);
        else
            r->skipCurrentElement();
    }
}
