//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Axis/BasicAxisItem.cpp
//! @brief     Implements various axis items.
//!
//! @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/Axis/BasicAxisItem.h"
#include "Base/Axis/MakeScale.h"
#include "Base/Axis/Scale.h"
#include "Base/Const/Units.h"
#include "GUI/Model/Util/UtilXML.h"

namespace {
namespace Tag {

const QString Nbins("Nbins");
const QString MinDeg("MinDeg");
const QString MaxDeg("MaxDeg");
const QString BaseData("BaseData");
const QString LockMinMax("LockMinMax");
const QString LogScale("LogScale");

} // namespace Tag
} // namespace

BasicAxisItem::BasicAxisItem(QObject* parent)
    : QObject(parent)
    , m_nbins(100)
{
    m_min.init("Min", "Minimum value of the axis", -1, 3, RealLimits::limitless(), "min");
    m_max.init("Max", "Maximum value of the axis", -2, 3, RealLimits::limitless(), "max");
}

BasicAxisItem::~BasicAxisItem() = default;

void BasicAxisItem::resize(size_t value)
{
    m_nbins = int(value);
}

void BasicAxisItem::setMin(double value)
{
    m_min.setAndNotify(value);
    emit axisRangeChanged();
}

void BasicAxisItem::setMax(double value)
{
    m_max.setAndNotify(value);
    emit axisRangeChanged();
}

Scale BasicAxisItem::makeScale(std::string name) const
{
    return EquiScan(name, size(), Units::deg2rad(min().dVal()), Units::deg2rad(max().dVal()));
}

void BasicAxisItem::writeTo(QXmlStreamWriter* w) const
{
    XML::writeTaggedValue(w, Tag::Nbins, m_nbins);
    m_min.writeTo2(w, Tag::MinDeg);
    m_max.writeTo2(w, Tag::MaxDeg);
}

void BasicAxisItem::readFrom(QXmlStreamReader* r)
{
    while (r->readNextStartElement()) {
        QString tag = r->name().toString();
        if (tag == Tag::Nbins)
            m_nbins = XML::readTaggedInt(r, tag);
        else if (tag == Tag::MinDeg)
            m_min.readFrom2(r, tag);
        else if (tag == Tag::MaxDeg)
            m_max.readFrom2(r, tag);
        else
            r->skipCurrentElement();
    }
}
