#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)
{
    s_ptMouseLast = event->scenePos();
    QList<QGraphicsItem *> items = scene->selectedItems();
    if (items.count() == 1)
    {
        QGraphicsItem *gitem = items.first();
        IShape *item = dynamic_cast<IShape *>(gitem);
        if(item)
        {
            //计算夹角
            QPointF originPoint = gitem->mapToScene(gitem->boundingRect().center());
            double dLengthY = s_ptMouseLast.y() - originPoint.y();
            double dLengthX = s_ptMouseLast.x() - originPoint.x();
            double dAngleMouseToItem = atan2(dLengthY, dLengthX) * 180 / M_PI;
            // if(atan2(dLengthY, dLengthX) < 0)
            //     dAngleMouseToItem += 360.0;

            double rotationAngle = gitem->rotation() + (dAngleMouseToItem - s_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++)
    {
        IShape *item = dynamic_cast<IShape *>(items.at(n));
        if(item)
        {
            item->removeOperationCopy();
        }
    }

    if (s_ptMouseLast != s_ptMouseDown)
        scene->notifyDocumentModified();

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