//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Overlay/VertexOverlay.cpp
//! @brief     Implements class VertexOverlay.
//!
//! @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/Overlay/VertexOverlay.h"
#include "GUI/Model/Mask/PointItem.h"
#include "GUI/View/Overlay/OverlayStyle.h"
#include "GUI/View/Plotter/ColorMap.h"
#include <QGraphicsSceneMouseEvent>
#include <QPainter>

VertexOverlay::VertexOverlay(PointItem* item, ColorMap* plot)
    : IOverlay(plot)
    , m_item(item)
    , m_on_hover(false)
{
    setFlag(QGraphicsItem::ItemIsMovable);
    setFlag(QGraphicsItem::ItemSendsGeometryChanges);
}

QRectF VertexOverlay::boundingRect() const
{
    return QRectF(-4, -4, 8, 8);
}

OverlayItem* VertexOverlay::parameterizedItem() const
{
    return m_item;
}

void VertexOverlay::updateParameterizedItem(const QPointF& pos)
{
    m_item->setPosX(m_plot->fromSceneX(pos.x()));
    m_item->setPosY(m_plot->fromSceneY(pos.y()));
}

void VertexOverlay::update_view()
{
    update();
}

void VertexOverlay::onPropertyChange()
{
    emit propertyChanged();
}

void VertexOverlay::paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*)
{
    painter->setRenderHints(QPainter::Antialiasing);
    QBrush brush = GUI::Overlay::getSelectionMarkerBrush();
    if (acceptHoverEvents() && m_on_hover)
        brush.setColor(Qt::red);
    painter->setBrush(brush);
    painter->setPen(GUI::Overlay::getSelectionMarkerPen());
    painter->drawEllipse(boundingRect());
}

void VertexOverlay::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
    updateParameterizedItem(event->scenePos());
}

void VertexOverlay::hoverEnterEvent(QGraphicsSceneHoverEvent* event)
{
    m_on_hover = true;
    emit closePolygonRequest(m_on_hover);
    IOverlay::hoverEnterEvent(event);
}

void VertexOverlay::hoverLeaveEvent(QGraphicsSceneHoverEvent* event)
{
    m_on_hover = false;
    emit closePolygonRequest(m_on_hover);
    IOverlay::hoverLeaveEvent(event);
}
