//  ************************************************************************************************
//
//  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/Mask/MasksSet.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/ColorMap.h"
#include "GUI/View/Plotter/ProjectionsPlot.h"
#include "GUI/View/Plotter/SavePlot.h"
#include "GUI/View/Scene/MaskGraphicsScene.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"

namespace {

void execContextMenu(const QPoint& point, FrameActions* actions, const MaskItem* item)
{
    QMenu menu;
    menu.addAction(actions->reset_view);
    menu.addAction(actions->save_plot);
    menu.addAction(actions->toggle_properties_panel);
    if (item)
        menu.addAction(actions->delete_mask);
    menu.exec(point);
}

} // namespace

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);

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

    int tabIndex = 0;

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

    if (m_data_source->isFromData()) {
        auto* masks_panel = new MasksPanel([this]() -> MasksSet* { return maskSet(); },
                                           m_data_source->isFromData(), true);
        m_panels->addTab(masks_panel, "Masks");
        m_panels->setTabToolTip(tabIndex++, "Masks panel");
        connect(masks_panel, &MasksPanel::deleteCurrentRequest, m_canvas2D->scene(),
                &MaskGraphicsScene::deleteCurrentItem);
    }

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

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

    updateFrame();


    //... Connect signals from toolbar

    connect(toolbar->actions()->toggle_properties_panel, &QAction::triggered, m_panels,
            &QWidget::setVisible);

    connect(toolbar, &Data2DToolbar::activityChanged, this, &Plot2DFrame::onActivityChanged);

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

    connect(toolbar->actions()->delete_mask, &QAction::triggered, m_canvas2D->scene(),
            &MaskGraphicsScene::deleteCurrentItem);

    connect(toolbar->actions()->raise_mask, &QAction::triggered, [this] { raiseMaskInStack(+1); });
    connect(toolbar->actions()->lower_mask, &QAction::triggered, [this] { raiseMaskInStack(-1); });

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

    connect(toolbar->actions()->save_plot, &QAction::triggered, [this] {
        ASSERT(data2DItem());
        GUI::Plot::savePlot(m_canvas2D->scene()->colorMap(), data2DItem()->c_field());
    });

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


    //... Connect signals from scene

    connect(m_canvas2D->scene(), &MaskGraphicsScene::switchPanelRequest, this,
            &Plot2DFrame::autoSwitchPanel, Qt::UniqueConnection);

    connect(m_canvas2D->scene(), &MaskGraphicsScene::itemContextMenuRequest,
            [toolbar](const QPoint& point, const MaskItem* item) {
                execContextMenu(point, toolbar->actions(), item);
            });


    //... Connect signals from 2D canvas

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

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

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


    //... Connect signals from 1D canvas

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


    //... Connect model, depending 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);
}

void Plot2DFrame::onActivityChanged(Canvas2DMode::Flag mode)
{
    m_canvas2D->setCanvasMode(mode);
    m_canvas1D->onActivityChanged(mode);

    if (Canvas2DMode::isMask(mode))
        autoSwitchPanel(1);
    if (Canvas2DMode::isPrjn(mode))
        autoSwitchPanel(2);
}

void Plot2DFrame::raiseMaskInStack(int relative_position)
{
    ASSERT(maskSet());
    if (!maskSet()->currentItem())
        return;

    maskSet()->move_current_to(size_t(maskSet()->currentIndex() + relative_position));
    m_canvas2D->scene()->updateOverlays();
}

void Plot2DFrame::updateFrame()
{
    if (!hasProperContext()) {
        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();
}

void Plot2DFrame::autoSwitchPanel(int to_panel)
{
    if (to_panel < m_panels->count() && m_panels->currentIndex() != 0)
        m_panels->setCurrentIndex(to_panel);
}

//  ************************************************************************************************
//  shortcuts
//  ************************************************************************************************

bool Plot2DFrame::hasProperContext() const
{
    return bool(dataSource()->realData2DItem() && !dataSource()->diffData2DItem());
}

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

MasksSet* Plot2DFrame::maskSet()
{
    return data2DItem() ? data2DItem()->masksRW() : nullptr;
}
