//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/SampleDesigner/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/SampleDesigner/MaterialInplaceForm.h"
#include "Base/Util/Assert.h"
#include "GUI/Model/Sample/ItemWithMaterial.h"
#include "GUI/Model/Sample/LayerItem.h"
#include "GUI/Model/Sample/MaterialItem.h"
#include "GUI/Model/Sample/MaterialModel.h"
#include "GUI/Model/Sample/SampleItem.h"
#include "GUI/Support/XML/Backup.h"
#include "GUI/View/MaterialEditor/MaterialEditorDialog.h"
#include "GUI/View/Numeric/DoubleLineEdit.h"
#include "GUI/View/Numeric/DoubleSpinBox.h"
#include "GUI/View/SampleDesigner/LayerEditorUtil.h"
#include "GUI/View/SampleDesigner/SampleEditorController.h"
#include "GUI/View/SampleDesigner/SampleForm.h"
#include "GUI/View/Tool/Globals.h"
#include "GUI/View/Tool/LayoutUtil.h"
#include <QGridLayout>
#include <QLabel>
#include <QPushButton>

MaterialInplaceForm::MaterialInplaceForm(QWidget* parent, ItemWithMaterial* item,
                                         SampleEditorController* ec)
    : QWidget(parent)
    , 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::onMaterialChanged);
}

ItemWithMaterial* MaterialInplaceForm::itemWithMaterial() const
{
    return m_item;
}

void MaterialInplaceForm::updateValues()
{
    for (auto* editor : findChildren<DoubleSpinBox*>()) {
        QSignalBlocker b(editor);
        editor->updateValue();
    }
    for (auto* editor : findChildren<DoubleLineEdit*>()) {
        QSignalBlocker b(editor);
        editor->updateBaseValue();
    }
}

void MaterialInplaceForm::selectMaterial()
{
    const auto materialsBackup = GUI::Util::createBackup(&m_ec->sampleItem()->materialModel());
    const QString newMaterialIdentifier = MaterialEditorDialog::chooseMaterial(
        GUI::Global::mainWindow, 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::onMaterialChanged);
        m_ec->sampleForm()->updateUnits(); // necessary on switch from refractive index to SLD
    } 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 DoubleLineEdit(this, *d);
        auto* label = new QLabel(d->label(), this);
        label->setBuddy(editor);

        QObject::connect(editor, &DoubleLineEdit::baseValueChanged, [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);
    if (layer_item && !layer_item->isTopLayer())
        LayerEditorUtil::addMagnetizationToGrid(m_layout, col, material->magnetization(),
                                                setNewValue, true, false, false);
    if (!layer_item)
        LayerEditorUtil::addMagnetizationToGrid(m_layout, col, material->magnetization(),
                                                setNewValue, true, false, true);

    // -- Create UI for material selection button
    auto* btn = new QPushButton("...", 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());
}

void MaterialInplaceForm::onMaterialChanged()
{
    updateValues();
}
