//  ************************************************************************************************
//
//  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 "Base/Util/Assert.h"
#include "Device/Data/Datafield.h"
#include "Device/IO/ReadWriteINT.h"
#include "GUI/Model/Util/UtilXML.h"
#include <sstream>

namespace {
namespace Tag {

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 df(std::vector<const Scale*>{m_axis->clone()});

    std::stringstream ss;
    Util::RW::writeBAInt(df, 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::writeBaseElement<BasicAxisItem>(w, XML::Tag::BaseData, this);

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

void PointwiseAxisItem::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::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)
{
    ASSERT(m_axis);
    ASSERT(m_axis->unit() != "bin");

    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()));
}
