//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Data/Data2DItem.cpp
//! @brief     Implements class Data2DItem.
//!
//! @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/Data/Data2DItem.h"
#include "Base/Axis/Scale.h"
#include "Base/Util/Assert.h"
#include "Device/Data/Datafield.h"
#include "GUI/Model/Axis/AmplitudeAxisItem.h"
#include "GUI/Model/Mask/MasksSet.h"
#include "GUI/Model/Util/UtilXML.h"

namespace {

namespace Tag {

const QString BaseData("BaseData");
const QString Interpolation("Interpolation");
const QString ZAxis("ZAxis");
const QString MaskContainer("MaskContainer");
const QString ProjectionContainer("ProjectionContainer");

} // namespace Tag

} // namespace

Data2DItem::Data2DItem()
    : DataItem(M_TYPE)
    , m_is_interpolated(true)
    , m_z_axis(std::make_unique<AmplitudeAxisItem>())
    , m_masks(std::make_unique<MasksSet>())
    , m_prjns(std::make_unique<MasksSet>())
{
}

Data2DItem::~Data2DItem() = default;

void Data2DItem::setDatafield(const Datafield& data)
{
    ASSERT(data.rank() == 2);
    setTheDatafield(data);
    updateAxesZoomLevel();
    updateDataRange();
}

double Data2DItem::xMin() const
{
    return m_datafield ? m_datafield->axis(0).min() : lowerX();
}

double Data2DItem::xMax() const
{
    return m_datafield ? m_datafield->axis(0).max() : upperX();
}

double Data2DItem::yMin() const
{
    return m_datafield ? m_datafield->axis(1).min() : lowerY();
}

double Data2DItem::yMax() const
{
    return m_datafield ? m_datafield->axis(1).max() : upperY();
}

double Data2DItem::lowerZ() const
{
    return zAxisItem()->min().dVal();
}

double Data2DItem::upperZ() const
{
    return zAxisItem()->max().dVal();
}

void Data2DItem::setZrange(double zmin, double zmax)
{
    if (lowerZ() == zmin && upperZ() == zmax)
        return;
    zAxisItem()->setMin(zmin);
    zAxisItem()->setMax(zmax);
}

void Data2DItem::copyZRangeFromItem(DataItem* sourceItem)
{
    const auto* source = dynamic_cast<Data2DItem*>(sourceItem);
    if (!source || source == this)
        return;
    setZrange(source->lowerZ(), source->upperZ());
}

bool Data2DItem::isZoomed() const
{
    return lowerX() > xMin() || upperX() < xMax() || lowerY() > yMin() || upperY() < yMax();
}

bool Data2DItem::isLog() const
{
    return zAxisItem()->isLogScale();
}

void Data2DItem::setLog(bool islog)
{
    zAxisItem()->setLogScale(islog);
}

void Data2DItem::setInterpolated(bool interp)
{
    m_is_interpolated = interp;
    emit interpolationChanged(interp);
}

bool Data2DItem::isZaxisLocked() const
{
    return m_z_axis->isLocked();
}

void Data2DItem::setZaxisLocked(bool state)
{
    return m_z_axis->setLocked(state);
}

//! Sets zoom range of X,Y axes, if it was not yet defined.

void Data2DItem::updateAxesZoomLevel()
{
    // set zoom range of x-axis to min, max values if it was not set already
    if (upperX() < lowerX())
        setXrange(xMin(), xMax());

    // set zoom range of y-axis to min, max values if it was not set already
    if (upperY() < lowerY())
        setYrange(yMin(), yMax());

    const int nx = static_cast<int>(m_datafield->axis(0).size());
    axItemX()->resize(nx);
    const int ny = static_cast<int>(m_datafield->axis(1).size());
    axItemY()->resize(ny);
}

//! Sets min,max values for z-axis, if axes is not locked, and ranges are not yet set.

void Data2DItem::updateDataRange()
{
    if (isZaxisLocked())
        return;

    computeDataRange();
}

void Data2DItem::computeDataRange()
{
    setZrange(dataRange().first, dataRange().second);
}

//! Init zmin, zmax to match the intensity values range.
std::pair<double, double> Data2DItem::dataRange() const
{
    const Datafield* data = c_field();

    const auto vec = data->flatVector();
    double min(*std::min_element(vec.cbegin(), vec.cend()));
    double max(*std::max_element(vec.cbegin(), vec.cend()));
    double logRange = pow(10, zAxisItem()->logRangeOrders().dVal());
    if (isLog()) {
        min = std::max(min, max / logRange);
        max *= 1.1;
    } else
        max *= 1.1;

    return {min, max};
}

size_t Data2DItem::axdim(int i) const
{
    if (i == 0)
        return axItemX()->size();
    else if (i == 1)
        return axItemY()->size();
    else
        ASSERT_NEVER;
}

void Data2DItem::resetView()
{
    if (!m_datafield)
        return;

    setAxesRangeToData();
    if (!isZaxisLocked())
        computeDataRange();
}

void Data2DItem::setAxesRangeToData()
{
    setXrange(xMin(), xMax());
    setYrange(yMin(), yMax());
}

void Data2DItem::writeTo(QXmlStreamWriter* w) const
{
    XML::writeBaseElement<DataItem>(w, XML::Tag::BaseData, this);
    XML::writeTaggedValue(w, Tag::Interpolation, m_is_interpolated);
    XML::writeTaggedElement(w, Tag::ZAxis, *m_z_axis);
    XML::writeTaggedElement(w, Tag::MaskContainer, *m_masks);
    XML::writeTaggedElement(w, Tag::ProjectionContainer, *m_prjns);
}

void Data2DItem::readFrom(QXmlStreamReader* r)
{
    while (r->readNextStartElement()) {
        QString tag = r->name().toString();
        if (tag == Tag::BaseData)
            XML::readBaseElement<DataItem>(r, tag, this);
        else if (tag == Tag::Interpolation)
            m_is_interpolated = XML::readTaggedBool(r, tag);
        else if (tag == Tag::ZAxis)
            XML::readTaggedElement(r, tag, *m_z_axis);
        else if (tag == Tag::MaskContainer)
            XML::readTaggedElement(r, tag, *m_masks);
        else if (tag == Tag::ProjectionContainer)
            XML::readTaggedElement(r, tag, *m_prjns);
        else
            r->skipCurrentElement();
    }
}
