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

MousyPlot::MousyPlot() {}

MousyPlot::~MousyPlot() = default;

void MousyPlot::setMouseTrackingEnabled(bool enable)
{
    setMouseTracking(enable);

    if (enable)
        connect(this, &QCustomPlot::mouseMove, this, &MousyPlot::onCustomMouseMove,
                Qt::UniqueConnection);
    else
        disconnect(this, &QCustomPlot::mouseMove, this, &MousyPlot::onCustomMouseMove);
}

void MousyPlot::replot()
{
    QCustomPlot::replot(QCustomPlot::rpQueuedReplot);
}

//! Processes a mouse move event. Emits signals depending on mouse position vs axes viewport.

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

    if (xAxis->range().contains(x) && yAxis->range().contains(y)) {
        if (!m_was_inside) {
            emit enteringPlot();
            m_was_inside = true;
        }
        emit positionChanged(x, y);

    } else {
        if (m_was_inside) {
            emit leavingPlot();
            m_was_inside = false;
        }
    }
}
