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

ScalingSelector::ScalingSelector(QObject *parent)
    : BaseSelector(parent)
{
    m_type = ST_scaling;
}
ScalingSelector::~ScalingSelector()
{

}

void ScalingSelector::mousePressEvent(QGraphicsSceneMouseEvent* event, DesignerScene* scene)
{
    BaseSelector::mousePressEvent(event,scene);
}

void ScalingSelector::mouseMoveEvent(QGraphicsSceneMouseEvent* event, DesignerScene* scene)
{
    ms_ptMouseLast = event->scenePos();
    QList<QGraphicsItem *> items = scene->selectedItems();
    if (items.count() == 1)
    {
        GraphicsBaseItem* item = qgraphicsitem_cast<GraphicsBaseItem*>(items.first());
        if(item)
        {
            if(ms_nDragHandle != H_none)
            {
                QPointF basePoint = item->getSymmetricPointPos(ms_nDragHandle);
                if(basePoint.x() == 0)
                    basePoint.setX(1);
                if(basePoint.y() == 0)
                    basePoint.setY(1);

                //计算缩放倍数
                QPointF iniDelta = item->mapFromScene(ms_ptMouseDown) - basePoint;
                QPointF lastDelta = item->mapFromScene(ms_ptMouseLast) - basePoint;
                double sx = lastDelta.x() / iniDelta.x();
                double sy = lastDelta.y() / iniDelta.y();

                item->resize(ms_nDragHandle, sx, sy, basePoint);
            }
        }
    }
}

void ScalingSelector::mouseReleaseEvent(QGraphicsSceneMouseEvent* event, DesignerScene* scene)
{
    QList<QGraphicsItem *> items = scene->selectedItems();
    if (items.count() == 1)
    {
        GraphicsBaseItem* item = qgraphicsitem_cast<GraphicsBaseItem*>(items.first());
        if(item && ms_ptMouseLast != ms_ptMouseDown)
        {
            item->updateCoordinate();
        }
    }

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