//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Tune/FitParameterItem.cpp
//! @brief     Implements classes FitTypeItem FitDoubleItem FitEditableDoubleItem FitParameterItem.
//!
//! @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/Tune/FitParameterItem.h"
#include "Base/Util/Assert.h"
#include "GUI/Model/Tune/FitParameterLinkItem.h"
#include "GUI/Model/Util/UtilXML.h"
#include <utility>

namespace {
namespace Tag {

const QString Value("Value");
const QString IsEnabled("IsEnabled");
const QString DisplayName("DisplayName");
const QString Type("Type");
const QString TypeItem("TypeItem");
const QString StartValue("StartValue");
const QString MinValue("MinValue");
const QString MaxValue("MaxValue");
const QString FitLinkItem("FitLinkItem");
const QString BaseData("BaseData");

} // namespace Tag
} // namespace

FitTypeItem::FitTypeItem(ComboProperty type, QObject* parent)
    : QObject(parent)
    , m_type(std::move(type))
{
    setObjectName("Type");
}

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

    // type
    w->writeStartElement(Tag::Type);
    m_type.writeTo(w);
    w->writeEndElement();
}

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

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

        // type
        if (tag == Tag::Type) {
            m_type.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}

//------------------------------------------------------------------------------------------------

FitDoubleItem::FitDoubleItem(double value, QObject* parent)
    : QObject(parent)
    , m_value(value)
    , m_decimals(3)
    , m_limits(RealLimits::limitless())
{
}

void FitDoubleItem::writeTo(QXmlStreamWriter* w) const
{
    // no need to write m_limits and m_decimals
    XML::writeAttribute(w, XML::Attrib::version, uint(1));

    // value
    w->writeStartElement(Tag::Value);
    XML::writeAttribute(w, XML::Attrib::value, m_value);
    w->writeEndElement();
}

void FitDoubleItem::readFrom(QXmlStreamReader* r)
{
    // no need to read m_limits and m_decimals
    const uint version = XML::readUIntAttribute(r, XML::Attrib::version);
    Q_UNUSED(version)

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

        // value
        if (tag == Tag::Value) {
            XML::readAttribute(r, XML::Attrib::value, &m_value);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}

//------------------------------------------------------------------------------------------------

FitEditableDoubleItem::FitEditableDoubleItem(double value, bool isEnabled, QObject* parent)
    : FitDoubleItem(value, parent)
    , m_is_enabled(isEnabled)
{
}

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

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

    // is enabled
    w->writeStartElement(Tag::IsEnabled);
    XML::writeAttribute(w, XML::Attrib::value, m_is_enabled);
    w->writeEndElement();
}

void FitEditableDoubleItem::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) {
            FitDoubleItem::readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // is enabled?
        } else if (tag == Tag::IsEnabled) {
            XML::readAttribute(r, XML::Attrib::value, &m_is_enabled);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}

//------------------------------------------------------------------------------------------------

namespace {

ComboProperty fitParameterTypeCombo()
{
    QStringList tooltips = QStringList() << "Fixed at given value"
                                         << "Limited in the range [min, max]"
                                         << "Limited at lower bound [min, inf]"
                                         << "Limited at upper bound [-inf, max]"
                                         << "No limits imposed to parameter value";

    ComboProperty result;
    result << "fixed"
           << "limited"
           << "lower limited"
           << "upper limited"
           << "free";
    result.setCurrentValue("limited");
    result.setToolTips(tooltips);
    return result;
}

const double range_factor = 0.5;

} // namespace


FitParameterItem::FitParameterItem(QObject* parent)
    : QObject(parent)
    , m_type_item(std::make_unique<FitTypeItem>(fitParameterTypeCombo(), this))
    , m_start_value_item(std::make_unique<FitDoubleItem>(0.0, this))
    , m_min_item(std::make_unique<FitEditableDoubleItem>(0.0, true, this))
    , m_max_item(std::make_unique<FitEditableDoubleItem>(0.0, false, this))
{
    setObjectName("FitParameter");
    m_start_value_item->setObjectName("Value");
    m_min_item->setObjectName("Min");
    m_max_item->setObjectName("Max");

    onTypeChange();
}

//! Inits P_MIN and P_MAX taking into account current value and external limits

void FitParameterItem::initMinMaxValues(const RealLimits& limits)
{
    double value = startValue();

    double dr(0);
    if (value == 0.0)
        dr = 1.0 * range_factor;
    else
        dr = std::abs(value) * range_factor;

    double min = value - dr;
    double max = value + dr;

    if (limits.hasLowerLimit() && min < limits.min())
        min = limits.min();

    if (limits.hasUpperLimit() && max > limits.max())
        max = limits.max();

    setMinimum(min);
    m_min_item->setLimits(limits);
    setMaximum(max);
    m_max_item->setLimits(limits);

    m_start_value_item->setLimits(limits);
}

//! Constructs Limits corresponding to current GUI settings.

AttLimits FitParameterItem::attLimits() const
{
    if (isFixed())
        return AttLimits::fixed();
    if (isLimited())
        return AttLimits::limited(minimum(), maximum());
    if (isLowerLimited())
        return AttLimits::lowerLimited(minimum());
    if (isUpperLimited())
        return AttLimits::upperLimited(maximum());
    if (isFree())
        return AttLimits::limitless();
    ASSERT_NEVER;
}

bool FitParameterItem::isValid() const
{
    if (isFixed() || isFree())
        return true;

    if (isLowerLimited())
        return minimum() <= startValue();
    if (isUpperLimited())
        return startValue() <= maximum();
    return minimum() <= startValue() && startValue() <= maximum();
}
void FitParameterItem::setDisplayName(QString displayName)
{
    m_display_name = displayName;
}

double FitParameterItem::startValue() const
{
    return m_start_value_item->value();
}

void FitParameterItem::setStartValue(double start_value)
{
    m_start_value_item->setValue(start_value);
}

QObject* FitParameterItem::startValueItem() const
{
    return m_start_value_item.get();
}

double FitParameterItem::minimum() const
{
    return m_min_item->value();
}

void FitParameterItem::setMinimum(double minimum)
{
    m_min_item->setValue(minimum);
}

QObject* FitParameterItem::minimumItem() const
{
    return m_min_item.get();
}

double FitParameterItem::maximum() const
{
    return m_max_item->value();
}

void FitParameterItem::setMaximum(double maximum)
{
    m_max_item->setValue(maximum);
}

QObject* FitParameterItem::maximumItem() const
{
    return m_max_item.get();
}

FitParameterLinkItem* FitParameterItem::addLinkItem(const QString& title, const QString& link)
{
    auto* newLink = new FitParameterLinkItem(this);
    m_links.push_back(newLink);

    newLink->setTitle(title);
    newLink->setLink(link);
    return newLink;
}

void FitParameterItem::removeLink(const QString& link)
{
    for (FitParameterLinkItem* linkItem : m_links)
        if (linkItem->link() == link)
            m_links.delete_element(linkItem);
}

QVector<FitParameterLinkItem*> FitParameterItem::linkItems() const
{
    return QVector<FitParameterLinkItem*>(m_links.begin(), m_links.end());
}

QStringList FitParameterItem::links() const
{
    QStringList links;
    for (FitParameterLinkItem* linkItem : linkItems())
        links << linkItem->link();
    return links;
}

void FitParameterItem::setTypeCombo(const ComboProperty& type)
{
    m_type_item->setType(type);
    onTypeChange();
}

QString FitParameterItem::currentType() const
{
    return m_type_item->type().currentValue();
}

QObject* FitParameterItem::typeItem() const
{
    return m_type_item.get();
}

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

    // displayName
    w->writeStartElement(Tag::DisplayName);
    XML::writeAttribute(w, XML::Attrib::value, m_display_name);
    w->writeEndElement();

    // type
    w->writeStartElement(Tag::TypeItem);
    m_type_item->writeTo(w);
    w->writeEndElement();

    // start value
    w->writeStartElement(Tag::StartValue);
    m_start_value_item->writeTo(w);
    w->writeEndElement();

    // min value
    w->writeStartElement(Tag::MinValue);
    m_min_item->writeTo(w);
    w->writeEndElement();

    // max value
    w->writeStartElement(Tag::MaxValue);
    m_max_item->writeTo(w);
    w->writeEndElement();

    // parameter links
    for (const auto* fitLink : linkItems()) {
        w->writeStartElement(Tag::FitLinkItem);
        w->writeAttribute(XML::Attrib::name, fitLink->title());
        fitLink->writeTo(w);
        w->writeEndElement();
    }
}

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

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

        // displayName
        if (tag == Tag::DisplayName) {
            XML::readAttribute(r, XML::Attrib::value, &m_display_name);
            XML::gotoEndElementOfTag(r, tag);

            // type
        } else if (tag == Tag::TypeItem) {
            m_type_item->readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // start value
        } else if (tag == Tag::StartValue) {
            m_start_value_item->readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // min value
        } else if (tag == Tag::MinValue) {
            m_min_item->readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // max value
        } else if (tag == Tag::MaxValue) {
            m_max_item->readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // parameter links
        } else if (tag == Tag::FitLinkItem) {
            addLinkItem("", "")->readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}

//! Enables/disables min, max properties on FitParameterItem's type

void FitParameterItem::onTypeChange()
{
    if (isFixed()) {
        setLimitEnabled(m_min_item.get(), false);
        setLimitEnabled(m_max_item.get(), false);
    }

    else if (isLimited()) {
        setLimitEnabled(m_min_item.get(), true);
        setLimitEnabled(m_max_item.get(), true);
    }

    else if (isLowerLimited()) {
        setLimitEnabled(m_min_item.get(), true);
        setLimitEnabled(m_max_item.get(), false);
    }

    else if (isUpperLimited()) {
        setLimitEnabled(m_min_item.get(), false);
        setLimitEnabled(m_max_item.get(), true);
    }

    else if (isFree()) {
        setLimitEnabled(m_min_item.get(), false);
        setLimitEnabled(m_max_item.get(), false);
    }
}

//! Set limit property with given name to the enabled state

void FitParameterItem::setLimitEnabled(FitEditableDoubleItem* propertyItem, bool enabled)
{
    ASSERT(propertyItem);
    propertyItem->setEnabled(enabled);
}

bool FitParameterItem::isLimited() const
{
    return currentType() == "limited";
}

bool FitParameterItem::isFree() const
{
    return currentType() == "free";
}

bool FitParameterItem::isLowerLimited() const
{
    return currentType() == "lower limited";
}

bool FitParameterItem::isUpperLimited() const
{
    return currentType() == "upper limited";
}

bool FitParameterItem::isFixed() const
{
    return currentType() == "fixed";
}
