//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Overlay/SizeHandle.cpp
//! @brief     Implements class SizeHandle.
//!
//! @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/SizeHandle.h"
#include "GUI/View/Overlay/OverlayStyle.h"
#include <QCursor>
#include <QGraphicsSceneMouseEvent>
#include <QPainter>
#include <array>

namespace {

const std::array<Qt::CursorShape, 8> cursors{
    Qt::SizeFDiagCursor, Qt::SizeVerCursor, Qt::SizeBDiagCursor, Qt::SizeHorCursor,
    Qt::SizeFDiagCursor, Qt::SizeVerCursor, Qt::SizeBDiagCursor, Qt::SizeHorCursor};

} // namespace


SizeHandle::SizeHandle(int i, QGraphicsObject* parent)
    : m_i(i)
{
    setParentItem(parent);
    hide();
    setCursor(::cursors[i]);
}

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

void SizeHandle::paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*)
{
    painter->setRenderHints(QPainter::Antialiasing);
    painter->setBrush(GUI::Overlay::getSelectionMarkerBrush());
    painter->setPen(GUI::Overlay::getSelectionMarkerPen());
    if (m_i % 2 == 1)
        painter->drawRect(boundingRect());
    else
        painter->drawEllipse(boundingRect());
}

void SizeHandle::mousePressEvent(QGraphicsSceneMouseEvent*)
{
    emit requestResizing(true);
}

void SizeHandle::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
    emit requestEnactResize(m_i, event->scenePos());
}

void SizeHandle::mouseReleaseEvent(QGraphicsSceneMouseEvent*)
{
    emit requestResizing(false);
}

void SizeHandle::updateHandlePosition(const QRectF& rect)
{
    switch (m_i) {
    case 0:
        setPos(rect.topLeft());
        break;
    case 1:
        setPos(QPointF(rect.x() + rect.width() / 2, rect.y()));
        break;
    case 2:
        setPos(rect.topRight());
        break;
    case 3:
        setPos(QPointF(rect.x() + rect.width(), rect.y() + rect.height() / 2));
        break;
    case 4:
        setPos(rect.bottomRight());
        break;
    case 5:
        setPos(QPointF(rect.x() + rect.width() / 2, rect.y() + rect.height()));
        break;
    case 6:
        setPos(rect.bottomLeft());
        break;
    case 7:
        setPos(QPointF(rect.x(), rect.y() + rect.height() / 2));
        break;
    }
}

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