//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Descriptor/AxisProperty.cpp
//! @brief     Implements class AxisProperty.
//!
//! @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/AxisProperty.h"
#include "Base/Axis/Scale.h"
#include "GUI/Model/Util/UtilXML.h"

namespace {
namespace Tag {

const QString Nbins("Nbins");
const QString Min("Min");
const QString Max("Max");
const QString ExpandGroupbox("ExpandGroupbox"); // obsolete since v22.0

} // namespace Tag
} // namespace

AxisProperty::AxisProperty() = default;

void AxisProperty::initMin(const QString& label, const QString& tooltip, double value,
                           const RealLimits& limits, uint decimals)
{
    m_min.init(label, tooltip, value, decimals, limits, "min");
}

void AxisProperty::initMax(const QString& label, const QString& tooltip, double value,
                           const RealLimits& limits, uint decimals)
{
    m_max.init(label, tooltip, value, decimals, limits, "max");
}

Scale AxisProperty::createAxis(const std::string& name) const
{
    return EquiDivision(name, m_nbins, m_min, m_max);
}

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

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

    // min
    w->writeStartElement(Tag::Min);
    m_min.writeTo(w);
    w->writeEndElement();

    // max
    w->writeStartElement(Tag::Max);
    m_max.writeTo(w);
    w->writeEndElement();
}

void AxisProperty::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);

            // min
        } else if (tag == Tag::Min) {
            m_min.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // max
        } else if (tag == Tag::Max) {
            m_max.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}
