//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Axis/PointwiseAxisItem.cpp
//! @brief     Implements pointwise axis item.
//!
//! @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/PointwiseAxisItem.h"
#include "Base/Axis/Frame.h"
#include "Base/Axis/MakeScale.h"
#include "Base/Axis/Scale.h"
#include "Base/Const/Units.h"
#include "Device/Data/Datafield.h"
#include "Device/IO/ReadWriteINT.h"
#include "GUI/Model/Util/UtilXML.h"
#include <sstream>

namespace {
namespace Tag {

const QString NativeUnits("NativeUnits"); // obsolete since v22.0
const QString BinaryData("BinaryData");
const QString BaseData("BaseData");

} // namespace Tag
} // namespace

PointwiseAxisItem::PointwiseAxisItem(QObject* parent)
    : BasicAxisItem(parent)
{
}

PointwiseAxisItem::~PointwiseAxisItem() = default;

void PointwiseAxisItem::setAxis(const Scale& axis)
{
    m_axis = std::unique_ptr<Scale>(axis.clone());
}

const Scale* PointwiseAxisItem::axis() const
{
    return m_axis.get();
}

QByteArray PointwiseAxisItem::serializeBinaryData() const
{
    if (!m_axis)
        return {};
    Datafield axisData({m_axis->clone()});

    std::stringstream ss;
    Util::RW::writeBAInt(axisData, ss);
    return {ss.str().c_str(), static_cast<int>(ss.str().size())};
}

void PointwiseAxisItem::deserializeBinaryData(const QByteArray& data)
{
    if (data.isEmpty())
        return;

    std::istringstream str(data.toStdString());
    Datafield d = Util::RW::readBAInt(str);
    m_axis = std::unique_ptr<Scale>(d.axis(0).clone());
}

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

    // parameters from base class
    w->writeStartElement(Tag::BaseData);
    BasicAxisItem::writeTo(w);
    w->writeEndElement();

    // axis binary data
    QByteArray a = serializeBinaryData();
    if (!a.isEmpty()) {
        w->writeStartElement(Tag::BinaryData);
        w->writeCharacters(a.toBase64());
        w->writeEndElement();
    }
}

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

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

        // parameters from base class
        if (tag == Tag::BaseData) {
            BasicAxisItem::readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // axis binary data
        } else if (tag == Tag::BinaryData) {
            QString valueAsBase64 = r->readElementText(QXmlStreamReader::SkipChildElements);
            const auto data = QByteArray::fromBase64(valueAsBase64.toLatin1());
            deserializeBinaryData(data);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}

void PointwiseAxisItem::updateAxIndicators(const Frame& frame)
{
    if (!m_axis || m_axis->unit() == "bin")
        return;

    if (frame.axis(0).unit() == "rad") {
        setMin(Units::rad2deg(frame.axis(0).min()));
        setMax(Units::rad2deg(frame.axis(0).max()));
    } else {
        setMin(frame.axis(0).min());
        setMax(frame.axis(0).max());
    }
    resize(static_cast<int>(m_axis->size()));
}
