//  ************************************************************************************************
//
//  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/File/DatafilesSet.h"
#include "GUI/Model/Project/DataSource.h"
#include "GUI/Model/Project/ProjectDocument.h"
#include "GUI/View/Canvas/SavePlotAssistant.h"
#include "GUI/View/Canvas/SpecularPlotCanvas.h"
#include "GUI/View/Setup/FrameActions.h"
#include <QVBoxLayout>
#include <qcustomplot.h>

SpecularDataCanvas::SpecularDataCanvas()
    : 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);
    setStyleSheet("background-color:white;");

    m_plot_canvas->setStatusLabelEnabled(true);

    connect(gActions->save_plot, &QAction::triggered, this, &SpecularDataCanvas::onSavePlotAction);

    enableDeprecatedOnMousePress(true); // true for legacy reasons

    connect(gDoc->datafiles(), &DatafilesSet::setChanged, this, &SpecularDataCanvas::setDataItem);
    setDataItem();
}

Data1DItem* SpecularDataCanvas::dataItem()
{
    return DataFromData().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::enableDeprecatedOnMousePress(bool b)
{
    if (b)
        connect(m_plot_canvas->customPlot(), &QCustomPlot::mousePress, this,
                &SpecularDataCanvas::onMousePress, Qt::UniqueConnection);
    else
        disconnect(m_plot_canvas->customPlot(), &QCustomPlot::mousePress, this,
                   &SpecularDataCanvas::onMousePress);
}

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

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