//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Sample/MaterialInplaceForm.cpp
//! @brief     Implements class MaterialInplaceForm.
//!
//! @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/Sample/MaterialInplaceForm.h"
#include "Base/Util/Assert.h"
#include "GUI/Model/Material/MaterialItem.h"
#include "GUI/Model/Material/MaterialsSet.h"
#include "GUI/Model/Sample/ItemWithMaterial.h"
#include "GUI/Model/Sample/LayerItem.h"
#include "GUI/Model/Sample/SampleItem.h"
#include "GUI/Model/Util/Backup.h"
#include "GUI/View/Base/LayoutUtil.h"
#include "GUI/View/Material/MaterialEditorDialog.h"
#include "GUI/View/Numeric/DoubleSpinBox.h"
#include "GUI/View/Sample/LayerEditorUtil.h"
#include "GUI/View/Sample/SampleEditorController.h"
#include "GUI/View/Sample/SampleForm.h"
#include <QLabel>
#include <QPushButton>

MaterialInplaceForm::MaterialInplaceForm(ItemWithMaterial* item, SampleEditorController* ec)
    : m_item(item)
    , m_ec(ec)
    , m_layout(new QGridLayout(this))
{
    m_layout->setContentsMargins(0, 0, 0, 0);
    createWidgets();

    connect(itemWithMaterial()->materialItem(), &MaterialItem::dataChanged, this,
            &MaterialInplaceForm::updateValues);
}
void MaterialInplaceForm::updateValues()
{
    for (auto* editor : findChildren<DoubleSpinBox*>()) {
        QSignalBlocker b(editor);
        editor->updateValue();
    }
}

void MaterialInplaceForm::selectMaterial()
{
    const auto materialsBackup = GUI::Util::createBackup(&m_ec->sampleItem()->materialModel());
    const QString newMaterialIdentifier =
        GUI::chooseMaterial(m_ec->sampleItem(), m_item->materialIdentifier());

    if (!newMaterialIdentifier.isEmpty() && newMaterialIdentifier != m_item->materialIdentifier()) {
        itemWithMaterial()->materialItem()->disconnect(this);
        GUI::Util::Layout::clearLayout(m_layout, true);
        m_ec->selectMaterial(m_item, newMaterialIdentifier);
        createWidgets();
        connect(itemWithMaterial()->materialItem(), &MaterialItem::dataChanged, this,
                &MaterialInplaceForm::updateValues);
    } else {
        updateValues(); // necessary, since in the material editor the values could have been
                        // changed without selecting a different material

        // If the list of materials was edited (e.g. a material added), but the current was not
        // changed, no modified signal would be sent. Check now for changes and emit if necessary.
        if (GUI::Util::createBackup(&m_ec->sampleItem()->materialModel()) != materialsBackup)
            m_ec->modified();
    }
}

void MaterialInplaceForm::createWidgets()
{
    auto* material = m_item->materialItem();
    ASSERT(material);

    // -- Create UI for delta/beta resp. sldRe/sldIm
    DoubleProperties values;
    if (material->hasRefractiveIndex())
        values << &material->delta() << &material->beta();
    else
        values << &material->sldRe() << &material->sldIm();

    int col = 0;
    for (DoubleProperty* d : values) {
        auto* editor = new DoubleSpinBox(&*d);
        auto* label = new QLabel(d->label(), this);
        label->setBuddy(editor);

        QObject::connect(editor, &DoubleSpinBox::valueChanged, [this, d](double newValue) {
            m_ec->setMaterialValue(m_item, newValue, *d);
        });

        m_layout->addWidget(label, 0, col);
        m_layout->addWidget(editor, 1, col++);
    }

    // -- Create UI for magnetization vector
    const auto setNewValue = [this](double value, DoubleProperty& d) {
        m_ec->setMaterialValue(m_item, value, d);
    };

    // Processing z-magnetization is not implemented yet (see issue #654)
    const LayerItem* layer_item = dynamic_cast<LayerItem*>(m_item);
    VectorProperty& v = material->magnetization();
    if (layer_item && !layer_item->isTopLayer())
        GUI::Util::Layer::addMultiPropertyToGrid(m_layout, col, {&v.x(), &v.y()}, setNewValue, true,
                                                 false);

    if (!layer_item)
        GUI::Util::Layer::addMultiPropertyToGrid(m_layout, col, {&v.x(), &v.y(), &v.z()},
                                                 setNewValue, true, false);

    // -- Create UI for material selection button
    auto* btn = new QPushButton("Editor", this);
    btn->setToolTip("Select material");
    m_layout->addWidget(btn, 1, m_layout->columnCount());
    connect(btn, &QPushButton::clicked, this, &MaterialInplaceForm::selectMaterial);

    m_layout->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding), 0, m_layout->columnCount());
}
