//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Frame/Plot2DFrame.cpp
//! @brief     Defines class Plot2DFrame.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "GUI/View/Frame/Plot2DFrame.h"
#include "Base/Util/Assert.h"
#include "GUI/Model/Data/Data2DItem.h"
#include "GUI/Model/File/DatafilesSet.h"
#include "GUI/Model/Job/JobsSet.h"
#include "GUI/Model/Project/DataSource.h"
#include "GUI/Model/Project/ProjectDocument.h"
#include "GUI/View/Canvas/MaskEditorCanvas.h"
#include "GUI/View/Canvas/ProjectedGraphsCanvas.h"
#include "GUI/View/IO/ProjectionsSaver.h"
#include "GUI/View/Plotter/ProjectionsPlot.h"
#include "GUI/View/Setup/AxesPanel.h"
#include "GUI/View/Setup/Data2DToolbar.h"
#include "GUI/View/Setup/FrameActions.h"
#include "GUI/View/Setup/MasksPanel.h"
#include <QHBoxLayout>
#include <QSplitter>
#include <QTabWidget>

Plot2DFrame::Plot2DFrame(std::unique_ptr<DataSource>&& data_source)
    : AnydataFrame(std::move(data_source))
    , m_canvas2D(new MaskEditorCanvas)
    , m_canvas1D(new ProjectedGraphsCanvas)
{
    auto* layout = new QHBoxLayout;
    setLayout(layout);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);

    auto* splitter = new QSplitter;
    layout->addWidget(splitter);
    splitter->setOrientation(Qt::Vertical);
    splitter->addWidget(m_canvas2D);
    splitter->addWidget(m_canvas1D);
    splitter->setCollapsible(0, false);
    splitter->setCollapsible(1, false);

    auto* panels = new QTabWidget;
    layout->addWidget(panels);
    panels->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum);
    panels->hide();

    int tabIndex = 0;

    auto* axes_panel = new AxesPanel(dataSource());
    panels->addTab(axes_panel, "Scales");
    panels->setTabToolTip(tabIndex++, "Scales panel");

    if (m_data_source->isFromData()) {
        auto* masks_panel = new MasksPanel(
            [this]() -> MasksSet* { return data2DItem() ? data2DItem()->masksRW() : nullptr; },
            true);
        panels->addTab(masks_panel, "Masks");
        panels->setTabToolTip(tabIndex++, "Masks panel");
        connect(masks_panel, &MasksPanel::deleteCurrentRequest, m_canvas2D,
                &MaskEditorCanvas::deleteCurrentItem);
    }

    auto* prjns_panel = new MasksPanel(
        [this]() -> MasksSet* { return data2DItem() ? data2DItem()->prjnsRW() : nullptr; }, false);
    panels->addTab(prjns_panel, "Prjns");
    panels->setTabToolTip(tabIndex++, "Projections panel");
    connect(prjns_panel, &MasksPanel::deleteCurrentRequest, m_canvas2D,
            &MaskEditorCanvas::deleteCurrentItem);

    auto* toolbar = new Data2DToolbar(m_data_source->isFromData());
    layout->addWidget(toolbar);

    //... Connections

    connect(toolbar->actions()->toggle_properties_panel, &QAction::triggered,
            [panels] { panels->setVisible(!panels->isVisible()); });

    connect(toolbar->actions()->save_plot, &QAction::triggered, m_canvas2D,
            &MaskEditorCanvas::exportPlot);

    connect(toolbar->actions()->save_projections, &QAction::triggered,
            [this] { m_canvas1D->currentProjectionsPlot()->exportPlot(); });

    connect(toolbar->actions()->reset_view, &QAction::triggered, m_canvas2D,
            &MaskEditorCanvas::onResetViewRequest);

    connect(toolbar, &Data2DToolbar::activityChanged, m_canvas2D, &MaskEditorCanvas::setCanvasMode);

    connect(toolbar, &Data2DToolbar::activityChanged, m_canvas1D,
            &ProjectedGraphsCanvas::onActivityChanged);

    connect(toolbar, &Data2DToolbar::requestMaskDisplay, m_canvas2D,
            &MaskEditorCanvas::changeMaskDisplay);

    connect(m_canvas2D, &MaskEditorCanvas::changeActivityRequest, toolbar,
            &Data2DToolbar::onChangeActivityRequest);

    connect(m_canvas2D, &MaskEditorCanvas::changeProjectionsTabRequest, m_canvas1D,
            &ProjectedGraphsCanvas::onActivityChanged);

    connect(m_canvas2D, &MaskEditorCanvas::marginsChanged, m_canvas1D,
            &ProjectedGraphsCanvas::onMarginsChanged);

    connect(m_canvas1D, &ProjectedGraphsCanvas::changeActivityRequest, toolbar,
            &Data2DToolbar::onProjectionTabChange);

    // subscription type depends on the context
    if (m_data_source->isFromData())
        connect(gDoc->datafiles(), &DatafilesSet::setChanged, this, &Plot2DFrame::updateFrame);
    else
        connect(gDoc->jobs(), &JobsSet::jobPlotContextChanged, this, &Plot2DFrame::updateFrame);

    updateFrame();
}

Data2DItem* Plot2DFrame::data2DItem()
{
    return dataSource()->realData2DItem();
}

void Plot2DFrame::updateFrame()
{
    if (!data2DItem()) {
        hide();
        return;
    }

    // The following line must come before setting context to the canvas!
    // It prevents problem with switching between datasets in projection mode.
    m_canvas1D->disconnectItem();

    m_canvas2D->updateCanvas(data2DItem());
    m_canvas1D->setData2DItem(data2DItem());

    show();
}
