//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Device/DistributionSelector.cpp
//! @brief     Implements class DistributionSelector.
//!
//! @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/View/Device/DistributionSelector.h"
#include "GUI/Model/Beam/BeamDistributionItem.h"
#include "GUI/Model/Descriptor/DistributionItems.h"
#include "GUI/Model/Util/Backup.h"
#include "GUI/View/Device/DistributionPlot.h"
#include "GUI/View/Numeric/ComboUtil.h"
#include "GUI/View/Numeric/DoubleSpinBox.h"
#include "GUI/View/Numeric/NumWidgetUtil.h"

DistributionSelector::DistributionSelector(std::optional<MeanConfig> mean_config,
                                           GUI::DistributionsCategory distributions,
                                           QWidget* parent, BeamDistributionItem* item,
                                           bool allow_distr)
    : QWidget(parent)
    , m_item(item)
    , m_mean_config(mean_config)
    , m_distributions(distributions)
{
    ASSERT(item);
    m_form_layout = new QFormLayout(this);
    m_form_layout->setContentsMargins(0, 0, 0, 0);

    m_distribution_combo = GUI::Util::createComboBoxFromProperty(
        item->distributionSelection(),
        [this](int) {
            createDistributionWidgets();
            emit distributionChanged();
        },
        true);
    m_distribution_combo->setEnabled(allow_distr);
    m_form_layout->addRow("Distribution:", m_distribution_combo);

    createDistributionWidgets();
}

void DistributionSelector::createDistributionWidgets()
{
    while (m_form_layout->rowCount() > 1)
        m_form_layout->removeRow(1);

    if (auto* it = dynamic_cast<DistributionCosineItem*>(m_item->distributionItem())) {
        createMeanSpinBox(it->mean());
        createSpinBox(it->hwhm());
        createNumSamplesSpinBox(it);
    } else if (auto* it = dynamic_cast<DistributionGateItem*>(m_item->distributionItem())) {
        auto* minSpinBox = createSpinBox(it->minimum());
        auto* maxSpinBox = createSpinBox(it->maximum());
        connect(minSpinBox, &DoubleSpinBox::valueChanged, [it, maxSpinBox](double d) {
            if (d > it->maximum()) {
                it->setMaximum(d);
                maxSpinBox->updateValue();
            }
        });
        connect(maxSpinBox, &DoubleSpinBox::valueChanged, [it, minSpinBox](double d) {
            if (d < it->minimum()) {
                it->setMinimum(d);
                minSpinBox->updateValue();
            }
        });
        createNumSamplesSpinBox(it);
    } else if (auto* it = dynamic_cast<DistributionGaussianItem*>(m_item->distributionItem())) {
        createMeanSpinBox(it->mean());
        createSpinBox(it->standardDeviation());
        createNumSamplesSpinBox(it);
        createSpinBox(it->relSamplingWidth());
    } else if (auto* it = dynamic_cast<DistributionLogNormalItem*>(m_item->distributionItem())) {
        createSpinBox(it->median());
        createSpinBox(it->scaleParameter());
        createNumSamplesSpinBox(it);
        createSpinBox(it->relSamplingWidth());
    } else if (auto* it = dynamic_cast<DistributionLorentzItem*>(m_item->distributionItem())) {
        createMeanSpinBox(it->mean());
        createSpinBox(it->hwhm());
        createNumSamplesSpinBox(it);
        createSpinBox(it->relSamplingWidth());
    } else if (auto* it = dynamic_cast<DistributionNoneItem*>(m_item->distributionItem())) {
        createMeanSpinBox(it->mean());
    } else if (auto* it = dynamic_cast<DistributionTrapezoidItem*>(m_item->distributionItem())) {
        createSpinBox(it->center());
        createSpinBox(it->leftWidth());
        createSpinBox(it->middleWidth());
        createSpinBox(it->rightWidth());
        createNumSamplesSpinBox(it);
    }
}

void DistributionSelector::createNumSamplesSpinBox(DistributionItem* dist)
{
    ASSERT(dist);
    m_form_layout->addRow("Number of samples:",
                          GUI::Util::createIntSpinBox([dist] { return dist->numberOfSamples(); },
                                                      [this, dist](int v) {
                                                          dist->setNumberOfSamples(v);
                                                          emit distributionChanged();
                                                      },
                                                      RealLimits::lowerLimited(1)));
}

DoubleSpinBox* DistributionSelector::createSpinBox(DoubleProperty& d)
{
    auto* sb = GUI::Util::createDoubleSpinBoxRow(m_form_layout, d);
    connect(sb, &DoubleSpinBox::valueChanged, [this, &d](double v) {
        d.setValue(v);
        emit distributionChanged();
    });
    return sb;
}

void DistributionSelector::createMeanSpinBox(DoubleProperty& d)
{
    if (m_mean_config) {
        if (m_mean_config->scientific) {
            auto* sb = GUI::Util::createDoubleSpinBoxRow(m_form_layout, d);
            connect(sb, &DoubleSpinBox::valueChanged, [this, &d](double v) {
                d.setValue(v);
                emit distributionChanged();
            });
        } else
            createSpinBox(d);
    }
}
void DistributionSelector::refresh()
{
    QSignalBlocker b(m_distribution_combo);
    m_distribution_combo->setCurrentIndex(m_item->distributionSelection().currentIndex());
    createDistributionWidgets();
}
