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

#include "GUI/Model/Descriptor/SpanProperty.h"
#include "GUI/Model/Util/UtilXML.h"

namespace {
namespace Tag {

const QString Nbins("Nbins");
const QString Width("Width");
const QString Center("Center");
const QString Min("Min");                       // from AxisProperty pre v22
const QString Max("Max");                       // from AxisProperty pre v22
const QString ExpandGroupbox("ExpandGroupbox"); // from AxisProperty pre v22

} // namespace Tag
} // namespace

SpanProperty::SpanProperty() = default;

void SpanProperty::initWidth(const QString& label, const QString& tooltip, double value,
                             const RealLimits& limits, uint decimals)
{
    m_width.init(label, tooltip, value, decimals, limits, "width");
}

void SpanProperty::initCenter(const QString& label, const QString& tooltip, double value,
                              const RealLimits& limits, uint decimals)
{
    m_center.init(label, tooltip, value, decimals, limits, "center");
}

void SpanProperty::writeTo(QXmlStreamWriter* w) const
{
    XML::writeAttribute(w, XML::Attrib::version, uint(3)); // forked from AxesProperty v3

    // nbins
    w->writeStartElement(Tag::Nbins);
    XML::writeAttribute(w, XML::Attrib::value, m_nbins);
    w->writeEndElement();

    // width
    w->writeStartElement(Tag::Width);
    m_width.writeTo(w);
    w->writeEndElement();

    // center
    w->writeStartElement(Tag::Center);
    m_center.writeTo(w);
    w->writeEndElement();
}

void SpanProperty::readFrom(QXmlStreamReader* r)
{
    const uint version = XML::readUIntAttribute(r, XML::Attrib::version);
    Q_UNUSED(version)

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

        // nbins
        if (tag == Tag::Nbins) {
            XML::readAttribute(r, XML::Attrib::value, &m_nbins);
            XML::gotoEndElementOfTag(r, tag);

            // width
        } else if (tag == Tag::Width) {
            m_width.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // center
        } else if (tag == Tag::Center) {
            m_center.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}
