#include "util/creatingSelector.h"
#include "graphicsItem/graphicsRectItem.h"
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsView>

CreatingSelector::CreatingSelector(QObject *parent)
    : BaseSelector(parent)
{
    m_type = ST_cerating;
    m_pCreatingItem = nullptr;
}
CreatingSelector::~CreatingSelector()
{

}

void CreatingSelector::mousePressEvent(QGraphicsSceneMouseEvent* event, DesignerScene* scene)
{
    if (event->button() != Qt::LeftButton)
        return;

    scene->clearSelection();
    ms_ptMouseDown = event->scenePos();
    ms_ptMouseLast = event->scenePos();

    switch (m_creatingType) {
    case GIT_rect:
        m_pCreatingItem = new GraphicsRectItem(QRect(1, 1, 1, 1));
        break;
    case GIT_roundRect:
        m_pCreatingItem = new GraphicsRectItem(QRect(1, 1, 1, 1), true);
        break;
    default:
        break;
    }

    ms_ptMouseDown += QPoint(2, 2);
    m_pCreatingItem->setPos(event->scenePos());
    scene->addItem(m_pCreatingItem);
    m_pCreatingItem->setSelected(true);

    ms_nDragHandle = H_rightBottom;
}

void CreatingSelector::mouseMoveEvent(QGraphicsSceneMouseEvent* event, DesignerScene* scene)
{
    setCursor(scene, Qt::CrossCursor);
    ms_ptMouseLast = event->scenePos();

    if (m_pCreatingItem)
    {

        QPointF basePoint = m_pCreatingItem->getSymmetricPointPos(ms_nDragHandle);
        if(basePoint.x() == 0)
            basePoint.setX(1);
        if(basePoint.y() == 0)
            basePoint.setY(1);

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

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

void CreatingSelector::mouseReleaseEvent(QGraphicsSceneMouseEvent* event, DesignerScene* scene)
{
    if (event->scenePos() == (ms_ptMouseDown - QPoint(2, 2))) //最小拖动范围
    {
        if(m_pCreatingItem)
        {
            m_pCreatingItem->setSelected(false);
            scene->removeItem(m_pCreatingItem);
            delete m_pCreatingItem;
        }
    }
    else if (m_pCreatingItem && ms_ptMouseLast != ms_ptMouseDown)
    {
        m_pCreatingItem->updateCoordinate();
        emit scene->signalAddItem(m_pCreatingItem);
    }

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