//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/SampleDesigner/InterferenceForm.cpp
//! @brief     Implements class InterferenceForm
//!
//! @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/SampleDesigner/InterferenceForm.h"
#include "GUI/Model/Sample/InterferenceItems.h"
#include "GUI/Model/Sample/Lattice2DItems.h"
#include "GUI/Model/Sample/ParticleLayoutItem.h"
#include "GUI/Support/Util/CustomEventFilters.h"
#include "GUI/View/Numeric/NumWidgetUtil.h"
#include "GUI/View/SampleDesigner/FormLayouter.h"
#include "GUI/View/SampleDesigner/LatticeTypeSelectionForm.h"
#include "GUI/View/SampleDesigner/SampleEditorController.h"
#include "GUI/View/SampleDesigner/SelectionContainerForm.h"
#include "GUI/View/Tool/GroupBoxCollapser.h"

InterferenceForm::InterferenceForm(QWidget* parent, ParticleLayoutItem* layoutItem,
                                   SampleEditorController* ec)
    : QGroupBox(parent)
    , m_layoutItem(layoutItem)
    , m_ec(ec)
{
    setTitle("Interference Function");

    FormLayouter layouter(this, ec);
    layouter.setContentsMargins(6, 6, 0, 6);
    m_collapser = GroupBoxCollapser::installIntoGroupBox(this);
    m_collapser->setExpanded(layoutItem->isExpandInterference());
    connect(m_collapser, &GroupBoxCollapser::toggled, this,
            [layoutItem](bool b) { layoutItem->setExpandInterference(b); });

    m_interferenceTypeCombo = new QComboBox(this);
    WheelEventEater::install(m_interferenceTypeCombo);
    const auto& d = layoutItem->interferenceSelection();
    m_interferenceTypeCombo->addItems(d.options());
    m_interferenceTypeCombo->setCurrentIndex(d.currentIndex());
    m_interferenceTypeCombo->setMaxVisibleItems(m_interferenceTypeCombo->count());
    m_interferenceTypeCombo->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
    layouter.addRow("Type:", m_interferenceTypeCombo);

    createInterferenceWidgets();
    updateTitle();

    connect(m_interferenceTypeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            [this](int newIndex) { m_ec->selectInterference(this, newIndex); });
}

ParticleLayoutItem* InterferenceForm::layoutItem() const
{
    return m_layoutItem;
}

void InterferenceForm::onInterferenceTypeChanged()
{
    FormLayouter layouter(this, m_ec);
    while (layouter.layout()->rowCount() > 1)
        layouter.layout()->removeRow(1);

    createInterferenceWidgets();
    updateTitle();
}

void InterferenceForm::createInterferenceWidgets()
{
    FormLayouter layouter(this, m_ec);
    auto* interference = m_layoutItem->interferenceSelection().currentItem();

    // Some values in interference settings affect the total density in the particle layout. To
    // provide all the updating (data & UI), the method
    // SampleEditorController::setDensityRelatedValueValue has to be called (instead of
    // SampleEditorController::setDouble). For this we have the following lambda to add a value:
    const auto addDensityRelatedValue = [this, &layouter, interference](DoubleProperty& d) {
        layouter.addValue(d, [this, interference, &d](double newValue) {
            m_ec->setDensityRelatedValue(interference, newValue, d);
        });
    };

    if (auto* itf = dynamic_cast<Interference1DLatticeItem*>(interference)) {
        layouter.addValue(itf->positionVariance());
        layouter.addValue(itf->length());
        layouter.addValue(itf->rotationAngle());
        layouter.addSelection(itf->decayFunctionSelection());
    } else if (auto* itf = dynamic_cast<InterferenceRadialParacrystalItem*>(interference)) {
        layouter.addValue(itf->positionVariance());
        layouter.addValue(itf->peakDistance());
        layouter.addValue(itf->dampingLength());
        layouter.addValue(itf->domainSize());
        layouter.addValue(itf->kappa());
        layouter.addSelection(itf->probabilityDistributionSelection());
    } else if (auto* itf = dynamic_cast<InterferenceHardDiskItem*>(interference)) {
        layouter.addValue(itf->positionVariance());
        layouter.addValue(itf->radius());
        addDensityRelatedValue(itf->density());
    } else if (auto* itf = dynamic_cast<Interference2DLatticeItem*>(interference)) {
        layouter.addValue(itf->positionVariance());
        auto* w = new LatticeTypeSelectionForm(this, itf, m_ec);
        layouter.addRow(itf->latticeTypeSelection().label(), w);
        layouter.addSelection(itf->decayFunctionSelection());
    } else if (auto* itf = dynamic_cast<InterferenceFinite2DLatticeItem*>(interference)) {
        layouter.addValue(itf->positionVariance());
        layouter.addRow("Domain size 1:",
                        GUI::Util::createIntSpinbox([itf] { return itf->domainSize1(); },
                                                    [this, itf](int v) {
                                                        itf->setDomainSize1(v);
                                                        emit m_ec->modified();
                                                    },
                                                    RealLimits::lowerLimited(1),
                                                    "Domain size 1 in number of unit cells"));
        layouter.addRow("Domain size 2:",
                        GUI::Util::createIntSpinbox([itf] { return itf->domainSize2(); },
                                                    [this, itf](int v) {
                                                        itf->setDomainSize2(v);
                                                        emit m_ec->modified();
                                                    },
                                                    RealLimits::lowerLimited(1),
                                                    "Domain size 2 in number of unit cells"));

        auto* w = new LatticeTypeSelectionForm(this, itf, m_ec);
        layouter.addRow(itf->latticeTypeSelection().label(), w);
    } else if (auto* itf = dynamic_cast<Interference2DParacrystalItem*>(interference)) {
        layouter.addValue(itf->positionVariance());
        layouter.addValue(itf->dampingLength());
        layouter.addValue(itf->domainSize1());
        layouter.addValue(itf->domainSize2());
        auto* w = new LatticeTypeSelectionForm(this, itf, m_ec);
        layouter.addRow(itf->latticeTypeSelection().label(), w);
        layouter.addSelection(itf->probabilityDistributionSelection1());
        layouter.addSelection(itf->probabilityDistributionSelection2());
    }
}

void InterferenceForm::updateTitle()
{
    m_collapser->setTitle("Interference Function (" + m_interferenceTypeCombo->currentText() + ")");
}
