//  ************************************************************************************************
//
//  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(const ComboProperty& type, QObject* parent)
    : QObject(parent)
    , m_type(type)
{
    setObjectName("Type");
}

void FitTypeItem::writeTo(QXmlStreamWriter* w) const
{
    XML::writeTaggedElement(w, Tag::Type, m_type);
}

void FitTypeItem::readFrom(QXmlStreamReader* r)
{
    while (r->readNextStartElement()) {
        QString tag = r->name().toString();
        if (tag == Tag::Type)
            XML::readTaggedElement(r, tag, m_type);
        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::writeTaggedValue(w, Tag::Value, m_value);
}

void FitDoubleItem::readFrom(QXmlStreamReader* r)
{
    // no need to read m_limits and m_decimals
    while (r->readNextStartElement()) {
        QString tag = r->name().toString();
        if (tag == Tag::Value)
            m_value = XML::readTaggedDouble(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::writeBaseElement<FitDoubleItem>(w, XML::Tag::BaseData, this);
    XML::writeTaggedValue(w, Tag::IsEnabled, m_is_enabled);
}

void FitEditableDoubleItem::readFrom(QXmlStreamReader* r)
{
    while (r->readNextStartElement()) {
        QString tag = r->name().toString();
        if (tag == Tag::BaseData)
            XML::readBaseElement<FitDoubleItem>(r, tag, this);
        else if (tag == Tag::IsEnabled)
            m_is_enabled = XML::readTaggedBool(r, tag);
        else
            r->skipCurrentElement();
    }
}

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

namespace {

ComboProperty fitParameterTypeCombo()
{
    auto result =
        ComboProperty::fromList({"fixed", "limited", "lower limited", "upper limited", "free"});
    result.setCurrentValue("limited");
    result.setToolTips({"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"});
    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->setDVal(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->setDVal(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->setDVal(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::writeTaggedValue(w, Tag::DisplayName, m_display_name);
    XML::writeTaggedElement(w, Tag::TypeItem, *m_type_item);
    XML::writeTaggedElement(w, Tag::StartValue, *m_start_value_item);
    XML::writeTaggedElement(w, Tag::MinValue, *m_min_item);
    XML::writeTaggedElement(w, Tag::MaxValue, *m_max_item);

    // 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)
{
    while (r->readNextStartElement()) {
        QString tag = r->name().toString();
        if (tag == Tag::DisplayName)
            m_display_name = XML::readTaggedString(r, tag);
        else if (tag == Tag::TypeItem)
            XML::readTaggedElement(r, tag, *m_type_item);
        else if (tag == Tag::StartValue)
            XML::readTaggedElement(r, tag, *m_start_value_item);
        else if (tag == Tag::MinValue)
            XML::readTaggedElement(r, tag, *m_min_item);
        else if (tag == Tag::MaxValue)
            XML::readTaggedElement(r, tag, *m_max_item);
        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";
}
