//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Plotter/ScientificPlot.cpp
//! @brief     Implements class ScientificPlot.
//!
//! @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/Plotter/ScientificPlot.h"
#include "GUI/View/Plotter/PlotEventHelper.h"
#include <QEvent>
#include <qcustomplot.h>

ScientificPlot::ScientificPlot(PLOT_TYPE plot_type)
    : m_qcp(new QCustomPlot)
    , m_plot_type(plot_type)
    , m_event_helper(new PlotEventHelper(this))
{
}

ScientificPlot::~ScientificPlot() = default;

void ScientificPlot::setMouseTrackingEnabled(bool enable)
{
    m_event_helper->setMouseTrackingEnabled(enable);
}

bool ScientificPlot::axesRangeContains(double xpos, double ypos) const
{
    return m_qcp->xAxis->range().contains(xpos) && m_qcp->yAxis->range().contains(ypos);
}

QRectF ScientificPlot::viewportRectangle() const
{
    const QCPRange xrange = m_qcp->xAxis->range();
    const QCPRange yrange = m_qcp->yAxis->range();
    const double left = m_qcp->xAxis->coordToPixel(xrange.lower);
    const double right = m_qcp->xAxis->coordToPixel(xrange.upper);
    const double top = m_qcp->yAxis->coordToPixel(yrange.upper);
    const double bottom = m_qcp->yAxis->coordToPixel(yrange.lower);
    return {left, top, right - left, bottom - top};
}

bool ScientificPlot::event(QEvent* event)
{
    emit repaint_request();
    return QWidget::event(event);
}

qreal ScientificPlot::toSceneX(qreal v) const
{
    return m_qcp->xAxis->coordToPixel(v);
}

qreal ScientificPlot::toSceneY(qreal v) const
{
    return m_qcp->yAxis->coordToPixel(v);
}

qreal ScientificPlot::fromSceneX(qreal p) const
{
    return m_qcp->xAxis->pixelToCoord(p);
}

qreal ScientificPlot::fromSceneY(qreal p) const
{
    return m_qcp->yAxis->pixelToCoord(p);
}

void ScientificPlot::replot()
{
    m_qcp->replot(QCustomPlot::rpQueuedReplot);
}
