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

#include "GUI/Model/Par/ParameterBackup.h"
#include "GUI/Model/Util/UtilXML.h"
#include <utility>

namespace {
namespace Tag {

const QString Title("Title");
const QString BackupValues("BackupValues");
const QString BackupValue("BackupValue");

} // namespace Tag
} // namespace

ParameterBackup::ParameterBackup(QString title)
    : m_title(std::move(title))
{
}

double ParameterBackup::value(const QString& link)
{
    return m_backup_values[link];
}

void ParameterBackup::setValue(const QString& link, double d)
{
    m_backup_values[link] = d;
}

bool ParameterBackup::contains(const QString& link)
{
    return m_backup_values.contains(link);
}

void ParameterBackup::writeTo(QXmlStreamWriter* w) const
{
    XML::writeAttribute(w, XML::Attrib::version, uint(1));

    // title
    w->writeStartElement(Tag::Title);
    XML::writeAttribute(w, XML::Attrib::value, m_title);
    w->writeEndElement();

    // values
    w->writeStartElement(Tag::BackupValues);
    for (auto v = m_backup_values.cbegin(); v != m_backup_values.cend(); v++) {
        w->writeEmptyElement(Tag::BackupValue);
        XML::writeAttribute(w, XML::Attrib::id, v.key());
        XML::writeAttribute(w, XML::Attrib::value, v.value());
    }
    w->writeEndElement();
}

void ParameterBackup::readFrom(QXmlStreamReader* r)
{
    m_backup_values.clear();

    const uint version = XML::readUIntAttribute(r, XML::Attrib::version);
    Q_UNUSED(version)

    while (r->readNextStartElement()) {
        QString tag = r->name().toString();

        // title
        if (tag == Tag::Title) {
            XML::readAttribute(r, XML::Attrib::value, &m_title);
            XML::gotoEndElementOfTag(r, tag);

            // values
        } else if (tag == Tag::BackupValues) {
            readValues(r);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}

void ParameterBackup::readValues(QXmlStreamReader* r)
{
    while (r->readNextStartElement()) {
        QString valTag = r->name().toString();

        if (valTag == Tag::BackupValue) {
            QString link;
            double d;
            XML::readAttribute(r, XML::Attrib::id, &link);
            XML::readAttribute(r, XML::Attrib::value, &d);
            m_backup_values[link] = d;
            XML::gotoEndElementOfTag(r, valTag);

        } else
            r->skipCurrentElement();
    }
}
