//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Sample/SampleEditor.cpp
//! @brief     Implements class SampleEditor.
//!
//! @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/SampleEditor.h"
#include "GUI/Model/Project/ProjectDocument.h"
#include "GUI/Model/Sample/LayerItem.h"
#include "GUI/Model/Sample/SampleItem.h"
#include "GUI/View/Sample/LayerEditorUtil.h"
#include "GUI/View/Sample/SampleEditorController.h"
#include "GUI/View/Sample/SampleForm.h"
#include "GUI/View/Widget/ApplicationSettings.h"
#include "GUI/View/Widget/StyledToolbar.h"
#include <QActionGroup>
#include <QBoxLayout>
#include <QPushButton>

SampleEditor::SampleEditor()
    : m_currentSampleWidget(nullptr)
{
    QScrollArea::setWidgetResizable(true);
    QScrollArea::setWidget(new QWidget());
}

SampleEditor::~SampleEditor()
{
    qDeleteAll(m_editControllers.values());
}

void SampleEditor::setCurrentSample(SampleItem* sampleItem)
{
    if (m_currentSample != nullptr)
        m_editControllers[m_currentSample]->setSampleForm(nullptr);

    m_currentSampleWidget = nullptr;
    delete QScrollArea::takeWidget();

    m_currentSample = sampleItem;
    if (m_currentSample == nullptr) {
        QScrollArea::setWidget(new QWidget());
        return;
    }

    if (!m_editControllers.contains(m_currentSample))
        m_editControllers.insert(m_currentSample, new SampleEditorController(m_currentSample));
    auto* ec = m_editControllers[m_currentSample];
    connect(ec, &SampleEditorController::requestViewInRealspace, this,
            &SampleEditor::requestViewInRealspace);
    connect(ec, &SampleEditorController::aboutToRemoveItem, this, &SampleEditor::aboutToRemoveItem);
    connect(ec, &SampleEditorController::modified, this, &SampleEditor::modified);

    createLayerColors();

    m_currentSampleWidget = new SampleForm(m_currentSample, ec);
    ec->setSampleForm(m_currentSampleWidget);
    m_currentSampleWidget->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
    QScrollArea::setWidget(m_currentSampleWidget);
}

void SampleEditor::createLayerColors() // #baLayerEditor move to better place
{
    if (!m_currentSample)
        return;

    int col = 0;
    for (auto* l : m_currentSample->layerItems()) {
        if (l->color().isValid())
            continue;

        l->setColor(LayerEditorUtil::predefinedLayerColors()[col]);
        col++;
        if (col == LayerEditorUtil::predefinedLayerColors().size())
            col = 0;
    }
}