//  ************************************************************************************************
//
//  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/Project/ProjectDocument.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/DSpinBox.h"
#include "GUI/View/Sample/LayerEditorUtil.h"
#include "GUI/View/Sample/SampleEditorController.h"
#include "GUI/View/Sample/SampleForm.h"
#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()
{
    auto* material = m_item->materialItem();
    ASSERT(material);

    for (auto* editor : findChildren<DSpinBox*>()) {
        QSignalBlocker b(editor);
        editor->updateValue();
    }
    for (auto* w : m_magnetic_widgets)
        w->setHidden(!material->isMagnetizatioEnabled());
    m_material_label->setText(material->matItemName());
}

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()) {
        disconnect(itemWithMaterial()->materialItem(), nullptr, this, nullptr);
        GUI::Util::Layout::clearLayout(m_layout, true);
        m_ec->selectMaterial(m_item, newMaterialIdentifier);
        createWidgets();
        connect(itemWithMaterial()->materialItem(), &MaterialItem::dataChanged, this,
                &MaterialInplaceForm::updateValues, Qt::UniqueConnection);
    } 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)
            gDoc->sampleChanged();
    }
}

void MaterialInplaceForm::createWidgets()
{
    m_magnetic_widgets.clear();

    auto* material = m_item->materialItem();
    ASSERT(material);

    int col = 0;
    m_material_label = new QLabel(material->matItemName());
    QFont f = m_material_label->font();
    f.setBold(true);
    m_material_label->setFont(f);
    m_layout->addWidget(m_material_label, 1, col++);

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

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

        QObject::connect(editor, &DSpinBox::valueChanged,
                         [this] { m_ec->setMaterialValue(m_item); });

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

    // -- Create UI for magnetization vector
    const auto setNewValue = [this] { m_ec->setMaterialValue(m_item); };

    // 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->isAmbient())
        m_magnetic_widgets.append(GUI::Util::Layer::addMultiPropertyToGrid(
            m_layout, col, {&v.x(), &v.y()}, true, false, setNewValue));

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

    // -- 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,
            Qt::UniqueConnection);

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

    updateValues();
}
