#include "util/selectorManager.h"
#include "util/creatingSelector.h"
#include "util/movingSelector.h"
#include "util/rotationSelector.h"
#include "util/scalingSelector.h"
#include "util/editingSelector.h"

SelectorManager*  SelectorManager::m_pInstance = nullptr;

SelectorManager::SelectorManager(QObject *parent)
    : QObject(parent)
{
    static CGarbo garbo; //用来是释放单例资源的静态成员变量

    //创建所有的selector
    BaseSelector* baseSelector = new BaseSelector(this);
    connect(baseSelector, SIGNAL(setWorkingSelector(SelectorType)), this, SLOT(onSignal_setWorkingSelector(SelectorType)));
    m_vecSelectors.push_back(baseSelector);
    CreatingSelector* creatingSelector = new CreatingSelector(this);
    connect(creatingSelector, SIGNAL(setWorkingSelector(SelectorType)), this, SLOT(onSignal_setWorkingSelector(SelectorType)));
    m_vecSelectors.push_back(creatingSelector);
    MovingSelector* movingSelector = new MovingSelector(this);
    connect(movingSelector, SIGNAL(setWorkingSelector(SelectorType)), this, SLOT(onSignal_setWorkingSelector(SelectorType)));
    m_vecSelectors.push_back(movingSelector);
    RotationSelector* rotationSelector = new RotationSelector(this);
    connect(rotationSelector, SIGNAL(setWorkingSelector(SelectorType)), this, SLOT(onSignal_setWorkingSelector(SelectorType)));
    m_vecSelectors.push_back(rotationSelector);
    ScalingSelector* scalingSelector = new ScalingSelector(this);
    connect(scalingSelector, SIGNAL(setWorkingSelector(SelectorType)), this, SLOT(onSignal_setWorkingSelector(SelectorType)));
    m_vecSelectors.push_back(scalingSelector);
    EditingSelector* editingSelector = new EditingSelector(this);
    connect(editingSelector, SIGNAL(setWorkingSelector(SelectorType)), this, SLOT(onSignal_setWorkingSelector(SelectorType)));
    m_vecSelectors.push_back(editingSelector);

    m_curSelector = ST_base;
}
SelectorManager::~SelectorManager()
{
    //析构所有的selector，因为是通过基类指针析构，所以基类的析构函数必须为虚函数
     // for(auto it = m_vecSelectors.begin(); it != m_vecSelectors.end(); it++)
     //    delete (*it);
}

SelectorManager* SelectorManager::getInstance()
{
    if(m_pInstance == nullptr)
    {
        m_pInstance = new SelectorManager();
    }
    return m_pInstance;
}

BaseSelector* SelectorManager::getWorkingSelector()
{
    for(auto it = m_vecSelectors.begin(); it != m_vecSelectors.end(); it++)
    {
        if((*it)->getSelectorType()==m_curSelector)
        {
            return (*it);
        }
    }

    return nullptr;
}

void SelectorManager::setDrawGraphicsItem(GraphicsItemType item)
{
    for(auto it = m_vecSelectors.begin(); it != m_vecSelectors.end(); it++)
    {
        if((*it)->getSelectorType()==ST_cerating)
        {
            CreatingSelector* creatingSelector = dynamic_cast<CreatingSelector*>(*it);
            creatingSelector->setCreatingItem(item);
        }
    }
}

void SelectorManager::onSignal_setWorkingSelector(SelectorType s)
{
    setWorkingSelector(s);
}
