//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Device/ResolutionForm.cpp
//! @brief     Implements class ResolutionForm
//!
//! @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/ResolutionForm.h"
#include "GUI/Model/Detector/DetectorItem.h"
#include "GUI/Model/Detector/ResolutionFunctionItems.h"
#include "GUI/View/Numeric/DoubleSpinBox.h"
#include "GUI/View/Numeric/NumWidgetUtil.h"
#include "GUI/View/Tool/GroupBoxCollapser.h"

ResolutionForm::ResolutionForm(Unit unit, QWidget* parent, DetectorItem* item)
    : QGroupBox("Resolution function", parent)
    , m_unit(unit)
    , m_item(item)
{
    ASSERT(item);
    m_formLayout = new QFormLayout(this);
    m_formLayout->setFieldGrowthPolicy(QFormLayout::FieldsStayAtSizeHint);

    auto* typeCombo =
        GUI::Util::createComboBoxFromProperty(item->resolutionFunctionSelection(), [this](int) {
            createResolutionWidgets();
            emit dataChanged();
        });
    m_formLayout->addRow("Type:", typeCombo);

    auto* collapser = GroupBoxCollapser::installIntoGroupBox(this);
    collapser->setExpanded(item->isExpandResolutionFunc());
    connect(collapser, &GroupBoxCollapser::toggled, this,
            [item](bool b) { item->setExpandResolutionFunc(b); });

    createResolutionWidgets();
}

void ResolutionForm::createResolutionWidgets()
{
    while (m_formLayout->rowCount() > 1)
        m_formLayout->removeRow(1);

    auto* resFunction = m_item->resolutionFunctionSelection().currentItem();
    if (auto* p = dynamic_cast<ResolutionFunction2DGaussianItem*>(resFunction)) {
        auto* sigmaXSpinBox = GUI::Util::createDoubleSpinBoxRow(m_formLayout, p->sigmaX());
        auto* sigmaYSpinBox = GUI::Util::createDoubleSpinBoxRow(m_formLayout, p->sigmaY());

        connect(sigmaXSpinBox, qOverload<double>(&DoubleSpinBox::baseValueChanged),
                [this, p](double newValue) {
                    p->setSigmaX(newValue);
                    emit dataChanged();
                });

        connect(sigmaYSpinBox, qOverload<double>(&DoubleSpinBox::baseValueChanged),
                [this, p](double newValue) {
                    p->setSigmaY(newValue);
                    emit dataChanged();
                });
    }
}
