//  ************************************************************************************************
//
//  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(const QString& title)
    : m_title(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::writeTaggedValue(w, Tag::Title, m_title);
    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();
    while (r->readNextStartElement()) {
        QString tag = r->name().toString();
        if (tag == Tag::Title)
            m_title = XML::readTaggedString(r, tag);
        else if (tag == Tag::BackupValues) {
            readValues(r);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}

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

        if (tag == Tag::BackupValue) {
            QString link = XML::readString(r, XML::Attrib::id);
            m_backup_values[link] = XML::readTaggedDouble(r, tag);

        } else
            r->skipCurrentElement();
    }
}
