//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Instrument/DetectorEditor.cpp
//! @brief     Implements class DetectorEditor
//!
//! @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/Instrument/DetectorEditor.h"
#include "GUI/Model/Detector/RectangularDetectorItem.h"
#include "GUI/Model/Detector/SphericalDetectorItem.h"
#include "GUI/Model/Device/InstrumentItems.h"
#include "GUI/View/Device/RectangularDetectorForm.h"
#include "GUI/View/Device/SphericalDetectorForm.h"
#include "GUI/View/Numeric/NumWidgetUtil.h"
#include "GUI/View/Tool/GroupBoxCollapser.h"


DetectorEditor::DetectorEditor(QWidget* parent, GISASInstrumentItem* instrument)
    : QGroupBox("Detector parameters", parent)
    , m_instrument(instrument)
{
    ASSERT(instrument);
    m_formLayout = new QFormLayout(this);

    auto* detectorTypeCombo =
        GUI::Util::createComboBoxFromProperty(instrument->detectorSelection(), [this](int) {
            createDetectorWidgets();
            emit dataChanged();
        });
    m_formLayout->addRow("Detector:", detectorTypeCombo);

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

    createDetectorWidgets();
}

void DetectorEditor::createDetectorWidgets()
{
    while (m_formLayout->rowCount() > 1)
        m_formLayout->removeRow(1);

    auto* detectorItem = m_instrument->detectorItem();
    if (auto* rect = dynamic_cast<RectangularDetectorItem*>(detectorItem)) {
        auto* editor = new RectangularDetectorForm(this, rect);
        m_formLayout->addRow(editor);
        connect(editor, &RectangularDetectorForm::dataChanged, this, &DetectorEditor::dataChanged);
    } else if (auto* spher = dynamic_cast<SphericalDetectorItem*>(detectorItem)) {
        auto* editor = new SphericalDetectorForm(this, spher);
        m_formLayout->addRow(editor);
        connect(editor, &SphericalDetectorForm::dataChanged, this, &DetectorEditor::dataChanged);
    } else
        ASSERT(false);
}
