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

ScalingSelector::ScalingSelector(QObject *parent)
    : BaseSelector(parent)
{
    m_type = ST_scaling;
    m_scalBasePoint = QPointF();
}
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)
    {
        AbstractShape* item = qgraphicsitem_cast<AbstractShape*>(items.first());
        if(item)
        {
            if(ms_nDragHandle != H_none)
            {
                if(m_scalBasePoint.isNull()) //基准点不能采用临时变量，因为handle的坐标也在不断变化，计算会出现问题
                {
                    m_scalBasePoint = item->getSymmetricPointPos(ms_nDragHandle);
                    if(m_scalBasePoint.x() == 0)
                        m_scalBasePoint.setX(1);
                    if(m_scalBasePoint.y() == 0)
                        m_scalBasePoint.setY(1);
                }

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

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

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

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