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

namespace {
namespace Tag {

const QString IsVisible("IsVisible");
const QString Nbins("Nbins");
const QString MinDeg("MinDeg");
const QString MaxDeg("MaxDeg");
const QString BaseData("BaseData");
const QString LockMinMax("LockMinMax");
const QString LogRangeOrders("LogRangeOrders");

} // namespace Tag
} // namespace


AmplitudeAxisItem::AmplitudeAxisItem(QObject* parent)
    : BasicAxisItem(parent)
    , m_lock_min_max(false)
    , m_visible(true)
{
    m_log_scale = true; // override base class
    m_log_range_orders.init("Log range", "", "Dynamic range to display values", 8, 3, true, 0.01,
                            RealLimits::nonnegative(), "logR");
}

void AmplitudeAxisItem::writeTo(QXmlStreamWriter* w) const
{
    XML::writeBaseElement<BasicAxisItem>(w, XML::Tag::BaseData, this);
    XML::writeTaggedValue(w, Tag::LockMinMax, m_lock_min_max);
    m_log_range_orders.writeTo2(w, Tag::LogRangeOrders);
    XML::writeTaggedValue(w, Tag::IsVisible, m_visible);
}

void AmplitudeAxisItem::readFrom(QXmlStreamReader* r)
{
    while (r->readNextStartElement()) {
        QString tag = r->name().toString();
        if (tag == Tag::BaseData)
            XML::readBaseElement<BasicAxisItem>(r, tag, this);
        else if (tag == Tag::LockMinMax)
            m_lock_min_max = XML::readTaggedBool(r, tag);
        else if (tag == Tag::LogRangeOrders)
            m_log_range_orders.readFrom2(r, tag);
        else if (tag == Tag::IsVisible)
            m_visible = XML::readTaggedBool(r, tag);
        else
            r->skipCurrentElement();
    }
}

void AmplitudeAxisItem::setLogRangeOrders(double v)
{
    m_log_range_orders.setAndNotify(v);
    setMin(max().dVal() / std::pow(10, m_log_range_orders.dVal()));
}

void AmplitudeAxisItem::adjustLogRangeOrders()
{
    if (min().dVal() > 0 && max().dVal() > 0)
        m_log_range_orders.setAndNotify(std::log10(max().dVal() / min().dVal()));
}

void AmplitudeAxisItem::setVisible(bool b)
{
    m_visible = b;
    emit axisVisibilityChanged();
}
