//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Sample/ParticleLayoutForm.cpp
//! @brief     Implements class ParticleLayoutForm.
//!
//! @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/ParticleLayoutForm.h"
#include "Base/Util/Assert.h"
#include "Base/Util/Vec.h"
#include "GUI/Model/Sample/InterferenceItems.h"
#include "GUI/Model/Sample/ItemWithParticles.h"
#include "GUI/Model/Sample/LayerItem.h"
#include "GUI/Model/Sample/ParticleLayoutItem.h"
#include "GUI/View/Base/ActionFactory.h"
#include "GUI/View/Numeric/DoubleSpinBox.h"
#include "GUI/View/Sample/HeinzFormLayout.h"
#include "GUI/View/Sample/InterferenceForm.h"
#include "GUI/View/Sample/LayerEditorUtil.h"
#include "GUI/View/Sample/LayerForm.h"
#include "GUI/View/Sample/SampleEditorController.h"
#include <QAction>
#include <QPushButton>

ParticleLayoutForm::ParticleLayoutForm(LayerForm* form, ParticleLayoutItem* t,
                                       SampleEditorController* ec)
    : CollapsibleGroupBox("TODO", form, t->expandParticleLayout)
    , m_layout(new HeinzFormLayout(ec))
    , m_layout_item(t)
    , m_ec(ec)
{
    body()->setLayout(m_layout);

    m_layout->addValue(m_layout_item->ownDensity());
    int rowOfTotalDensity = m_layout->rowCount() - 1;
    m_total_density_spin_box =
        m_layout->widgetAt<DoubleSpinBox*>(rowOfTotalDensity, QFormLayout::FieldRole);
    ASSERT(m_total_density_spin_box);

    m_layout->addRow(new InterferenceForm(this, t, ec));

    for (auto* particle : m_layout_item->itemsWithParticles())
        m_layout->addRow(
            GUI::Util::Layer::createWidgetForItemWithParticles(this, particle, true, ec));

    auto* btn = GUI::Util::Layer::createAddParticleButton(
        this, [=](FormfactorsCatalog::Type type) { ec->addParticleLayoutItem(t, type); },
        [=](ParticlesCatalog::Type type) { ec->addParticleLayoutItem(t, type); });
    m_structure_editing_widgets << btn;
    m_layout->addStructureEditingRow(btn);

    //... top right corner actions

    // show in real space
    {
        auto* showInRealspaceAction = ActionFactory::createShowInRealspaceAction(
            this, "particle layout", [ec, t] { ec->requestViewInRealspace(t); });
        addTitleAction(showInRealspaceAction);
    }
    // duplicate
    {
        m_duplicate_action = ActionFactory::createDuplicateAction(
            this, "particle layout", [ec, t, form] { ec->duplicateLayoutItem(form, t); });
        addTitleAction(m_duplicate_action);
    }
    // remove
    {
        m_remove_action = ActionFactory::createRemoveAction(
            this, "particle layout", [ec, t, form] { ec->removeLayoutItem(form, t); });
        addTitleAction(m_remove_action);
    }

    updateDensityEnabling();
    updateTitle(form->layerItem());
}

void ParticleLayoutForm::onParticleAdded(ItemWithParticles* t)
{
    int index = Vec::indexOfPtr(t, m_layout_item->itemsWithParticles());
    const int rowInLayout = m_layout->rowCount() - 1
                            - (m_layout_item->itemsWithParticles().size() - 1) + index; // -1: btn

    m_layout->insertRow(rowInLayout,
                        GUI::Util::Layer::createWidgetForItemWithParticles(this, t, true, m_ec));
}

void ParticleLayoutForm::onAboutToRemoveParticle(ItemWithParticles* t)
{
    int index = Vec::indexOfPtr(t, m_layout_item->itemsWithParticles());
    const int rowInLayout =
        m_layout->rowCount() - m_layout_item->itemsWithParticles().size() - 1 + index; // -1: btn

    m_layout->removeRow(rowInLayout);
}

void ParticleLayoutForm::updateDensityEnabling()
{
    m_total_density_spin_box->setEnabled(!m_layout_item->totalDensityIsDefinedByInterference());
}

void ParticleLayoutForm::updateDensityValue()
{
    if (m_layout_item->totalDensityIsDefinedByInterference())
        m_layout_item->setOwnDensity(m_layout_item->totalDensityValue());

    m_total_density_spin_box->updateValue();
}

void ParticleLayoutForm::updateTitle(const LayerItem* layerItem)
{
    const auto layouts = layerItem->layoutItems();
    if (layouts.size() > 1)
        setTitle("Particle layout " + QString::number(Vec::indexOfPtr(m_layout_item, layouts) + 1));
    else
        setTitle("Particle layout");
}
