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

FootprintForm::FootprintForm(QWidget* parent, SourceItem* item)
    : QGroupBox("Footprint correction", parent)
    , m_item(item)
{
    ASSERT(item);
    m_formLayout = new QFormLayout(this);
    m_formLayout->setFieldGrowthPolicy(QFormLayout::FieldsStayAtSizeHint);
    ASSERT(item->footprintSelection().currentItem());
    auto* typeCombo =
        GUI::Util::createComboBoxFromProperty(item->footprintSelection(), [this](int) {
            createFootprintWidgets();
            emit dataChanged();
        });
    m_formLayout->addRow("Type:", typeCombo);

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

    createFootprintWidgets();
}

void FootprintForm::createFootprintWidgets()
{
    while (m_formLayout->rowCount() > 1)
        m_formLayout->removeRow(1);

    auto* footprintItem = m_item->footprintSelection().currentItem();
    if (auto* square = dynamic_cast<FootprintSquareItem*>(footprintItem)) {
        auto* spinbox = new DoubleSpinBox(square->squareFootprintValue());
        spinbox->setSingleStep(0.01);
        m_formLayout->addRow("Width ratio:", spinbox);
        connect(spinbox, qOverload<double>(&DoubleSpinBox::baseValueChanged),
                [this, square](double newValue) {
                    square->setSquareFootprintValue(newValue);
                    emit dataChanged();
                });
    } else if (auto* gauss = dynamic_cast<FootprintGaussianItem*>(footprintItem)) {
        auto* spinbox = new DoubleSpinBox(gauss->gaussianFootprintValue());
        spinbox->setSingleStep(0.01);
        m_formLayout->addRow("Width ratio:", spinbox);
        connect(spinbox, qOverload<double>(&DoubleSpinBox::baseValueChanged),
                [this, gauss](double newValue) {
                    gauss->setGaussianFootprintValue(newValue);
                    emit dataChanged();
                });
    }
}
