//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Canvas/SpecularDataCanvas.cpp
//! @brief     Implements class SpecularDataCanvas.
//!
//! @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/Canvas/SpecularDataCanvas.h"
#include "Base/Util/Assert.h"
#include "GUI/Model/Data/Data1DItem.h"
#include "GUI/Model/Project/DataSource.h"
#include "GUI/Model/Project/ProjectDocument.h"
#include "GUI/View/Canvas/SpecularPlotCanvas.h"
#include "GUI/View/Plotter/SavePlot.h"
#include "GUI/View/Plotter/SpecularPlot.h"
#include "GUI/View/Setup/FrameActions.h"
#include <QVBoxLayout>
#include <qcustomplot.h>

SpecularDataCanvas::SpecularDataCanvas(const DataSource* data_source)
    : m_data_source(data_source)
    , m_plot_canvas(new SpecularPlotCanvas)
{
    auto* vlayout = new QVBoxLayout(this);
    vlayout->setContentsMargins(0, 0, 0, 0);
    vlayout->setSpacing(0);
    vlayout->addWidget(m_plot_canvas);
    setLayout(vlayout);

    // TODO: Only for legacy reasons the onMousePress handler is enabled.
    // It is deprecated because:
    // * mousepress is the wrong event to listen to for opening a context menu;
    // * it prevents us from getting context menu events for specific parts of the plot
    // (e.g. context menu for axis configuration).
    connect(m_plot_canvas->specularPlot(), &QCustomPlot::mousePress, this,
            &SpecularDataCanvas::onMousePress, Qt::UniqueConnection);

    setDataItem();
}

Data1DItem* SpecularDataCanvas::dataItem()
{
    ASSERT(m_data_source);
    return m_data_source->realData1DItem();
}

void SpecularDataCanvas::setDataItem()
{
    if (dataItem()) {
        m_plot_canvas->setData1DItems({dataItem()});
        m_plot_canvas->show();
    } else
        m_plot_canvas->hide();
}

QSize SpecularDataCanvas::sizeHint() const
{
    return {500, 400};
}

QSize SpecularDataCanvas::minimumSizeHint() const
{
    return {128, 128};
}

void SpecularDataCanvas::onSavePlotAction()
{
    ASSERT(dataItem());
    GUI::Plot::savePlot(m_plot_canvas->specularPlot(), dataItem()->c_field());
}

void SpecularDataCanvas::onMousePress(QMouseEvent* event)
{
    if (event->button() == Qt::RightButton)
        emit customContextMenuRequested(event->globalPos());
}

void SpecularDataCanvas::onResetView()
{
    m_plot_canvas->specularPlot()->currentData1DItem()->resetView();
}
