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

PlotEventHelper::PlotEventHelper(ScientificPlot* scientific_plot)
    : m_plot(scientific_plot)
{
}

PlotEventHelper::~PlotEventHelper() = default;

//! Sets tracking of the mouse for parent DescriptedPlot

void PlotEventHelper::setMouseTrackingEnabled(bool enable)
{
    m_plot->setMouseTracking(enable);
    m_plot->customPlot()->setMouseTracking(enable);

    if (enable)
        connect(m_plot->customPlot(), &QCustomPlot::mouseMove, this,
                &PlotEventHelper::onCustomMouseMove, Qt::UniqueConnection);
    else
        disconnect(m_plot->customPlot(), &QCustomPlot::mouseMove, this,
                   &PlotEventHelper::onCustomMouseMove);
}

//! Constructs status string on mouse move event coming from QCustomPlot. String is emitted
//! if mouse is in axes's viewport rectangle. Once mouse goes out of it, an
//! empty string is emitted once again.

void PlotEventHelper::onCustomMouseMove(QMouseEvent* event)
{
    double x = m_plot->customPlot()->xAxis->pixelToCoord(event->pos().x());
    double y = m_plot->customPlot()->yAxis->pixelToCoord(event->pos().y());

    if (m_plot->axesRangeContains(x, y)) {
        m_plot->statusString(m_plot->infoString(event->pos()));
        if (!m_was_inside) {
            enteringPlot();
            m_was_inside = true;
        }
        positionChanged(x, y);

    } else {
        if (m_was_inside) {
            m_plot->statusString("");
            leavingPlot();
            m_was_inside = false;
        }
    }
}
