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

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

}

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

void ScalingSelector::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)
        {
            if(s_nDragHandle != H_none)
            {
                if(m_scaleBasePoint.isNull()) //基准点不能采用临时变量，因为handle的坐标也在不断变化，计算会出现问题
                {
                    m_scaleBasePoint = item->getSymmetricPointPos(s_nDragHandle);
                    if(m_scaleBasePoint.x() == 0)
                        m_scaleBasePoint.setX(1);
                    if(m_scaleBasePoint.y() == 0)
                        m_scaleBasePoint.setY(1);
                }

                //计算缩放倍数
                QPointF iniDelta = gitem->mapFromScene(s_ptMouseDown) - m_scaleBasePoint;
                QPointF lastDelta = gitem->mapFromScene(s_ptMouseLast) - m_scaleBasePoint;
                double sx = lastDelta.x() / iniDelta.x();
                double sy = lastDelta.y() / iniDelta.y();

                item->resize(s_nDragHandle, sx, sy, m_scaleBasePoint);
            }
        }
    }
}

void ScalingSelector::mouseReleaseEvent(QGraphicsSceneMouseEvent* event, DesignerScene* scene)
{
    QList<QGraphicsItem *> items = scene->selectedItems();
    if (items.count() == 1)
    {
        IShape *item = dynamic_cast<IShape *>(items.first());
        if(item && s_ptMouseLast != s_ptMouseDown)
        {
            item->updateCoordinate();
            scene->notifyDocumentModified();
        }
    }

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