#include "util/rotationSelector.h"
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsView>
#include <graphicsItem/graphicsBaseItem.h>

RotationSelector::RotationSelector(QObject *parent)
    : BaseSelector(parent)
{
    m_type = ST_rotation;
}
RotationSelector::~RotationSelector()
{

}

void RotationSelector::mousePressEvent(QGraphicsSceneMouseEvent* event, DesignerScene* scene)
{

}

void RotationSelector::mouseMoveEvent(QGraphicsSceneMouseEvent* event, DesignerScene* scene)
{
    ms_ptMouseLast = event->scenePos();
    QList<QGraphicsItem *> items = scene->selectedItems();
    if (items.count() == 1)
    {
        AbstractShape* item = qgraphicsitem_cast<AbstractShape*>(items.first());
        if(item)
        {
            //计算夹角
            QPointF originPoint = item->mapToScene(item->boundingRect().center());
            double dLengthY = ms_ptMouseLast.y() - originPoint.y();
            double dLengthX = ms_ptMouseLast.x() - originPoint.x();
            double dAngleMouseToItem = atan2(dLengthY, dLengthX) * 180 / M_PI;
            // if(atan2(dLengthY, dLengthX) < 0)
            //     dAngleMouseToItem += 360.0;

            double rotationAngle = item->rotation() + (dAngleMouseToItem - ms_dAngleMouseDownToItem);
            //让角度保持在正负180的区间，也就是上下两个半圈，这样易于象限判断
            if (rotationAngle > 180)
                rotationAngle -= 360;
            if (rotationAngle < -180)
                rotationAngle += 360;

            item->rotateOperationCopy(rotationAngle);
            //qDebug() << "rotationAngle: " << rotationAngle;
        }
    }
}

void RotationSelector::mouseReleaseEvent(QGraphicsSceneMouseEvent* event, DesignerScene* scene)
{
    QList<QGraphicsItem *> items = scene->selectedItems();
    for(int n = 0; n < items.size(); n++)
    {
        AbstractShape* item = qgraphicsitem_cast<AbstractShape*>(items.at(n));
        if(item)
        {
            item->removeOperationCopy();
        }

    }

    ms_nDragHandle = H_none;
    setCursor(scene, Qt::ArrowCursor);
    emit setWorkingSelector(ST_base);
}
