//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Numeric/DoubleLineEdit.cpp
//! @brief     Implements class DoubleLineEdit
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2021
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "GUI/View/Numeric/DoubleLineEdit.h"
#include <QDoubleValidator>

DoubleLineEdit::DoubleLineEdit(QWidget* parent, const DoubleProperty& d)
    : QLineEdit(parent)
    , m_valueProperty(d)
{
    m_validator = new QDoubleValidator(0.0, 1e200, 1000, this);
    m_validator->setNotation(QDoubleValidator::ScientificNotation);
    const double minimum =
        d.limits().hasLowerLimit() ? std::max(d.limits().lowerLimit(), -1e200) : -1e200;
    const double maximum =
        d.limits().hasUpperLimit() ? std::min(d.limits().upperLimit(), +1e200) : +1e200;
    m_validator->setRange(minimum, maximum, 1000);
    setValidator(m_validator);

    setToolTip(d.tooltip());

    updateBaseValue();

    connect(this, &QLineEdit::editingFinished, this, &DoubleLineEdit::onEditingFinished);
}

void DoubleLineEdit::setBaseValue(double baseValue)
{
    setText(QString::number(baseValue, 'g'));
}

void DoubleLineEdit::updateBaseValue()
{
    setBaseValue(m_valueProperty.value());
}

QString DoubleLineEdit::displayUnitAsString() const
{
    if (std::holds_alternative<QString>(m_valueProperty.unit()))
        return std::get<QString>(m_valueProperty.unit());

    return unitAsString(std::get<Unit>(m_valueProperty.unit()));
}

void DoubleLineEdit::onEditingFinished()
{
    const double new_value = text().toDouble();
    if (new_value != m_valueProperty.value())
        emit baseValueChanged(new_value);
}
