//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Device/BackgroundForm.cpp
//! @brief     Implements class BackgroundForm
//!
//! @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/Device/BackgroundForm.h"
#include "GUI/Model/Device/BackgroundItems.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"

BackgroundForm::BackgroundForm(QWidget* parent, InstrumentItem* instrument)
    : QGroupBox("Environment", parent)
    , m_instrument(instrument)
{
    ASSERT(instrument);
    m_formLayout = new QFormLayout(this);
    m_formLayout->setFieldGrowthPolicy(QFormLayout::FieldsStayAtSizeHint);

    auto* backgroundTypeCombo =
        GUI::Util::createComboBoxFromProperty(instrument->backgroundSelection(), [this](int) {
            createBackgroundWidgets();
            emit dataChanged();
        });
    m_formLayout->addRow("Background type:", backgroundTypeCombo);

    createBackgroundWidgets();
    auto* collapser = GroupBoxCollapser::installIntoGroupBox(this);
    collapser->setExpanded(instrument->isExpandEnvironment());
    connect(collapser, &GroupBoxCollapser::toggled, this,
            [instrument](bool b) { instrument->setExpandEnvironment(b); });
}

void BackgroundForm::createBackgroundWidgets()
{
    while (m_formLayout->rowCount() > 1)
        m_formLayout->removeRow(1);

    auto* backgroundItem = m_instrument->backgroundItem();
    if (auto* p = dynamic_cast<ConstantBackgroundItem*>(backgroundItem)) {
        auto* spinbox = new DoubleSpinBox(p->backgroundValue());
        spinbox->setSingleStep(0.01);
        m_formLayout->addRow("Background value:", spinbox);

        connect(spinbox, &DoubleSpinBox::baseValueChanged, [this, p](double newValue) {
            p->setBackgroundValue(newValue);
            emit dataChanged();
        });
    }
}
