#include "itemmanager.h"

namespace ItemManager {
QVector<QCPItemText*> _QCPItemTextVtr;
QVector<QCPItemLine*> _QCPItemLineVtr;
QVector<QCPGraph*> _QCPGraphVtr;

void addTemporaryQCPItemText(QCPItemText *item,const QString objectName)
{
    item->setObjectName(TemporaryStr + Separator + objectName);
    _QCPItemTextVtr.push_back(item);
}

void addTemporaryQCPItemLine(QCPItemLine *item,const QString objectName)
{
    item->setObjectName(TemporaryStr + Separator + objectName);
    _QCPItemLineVtr.push_back(item);
}

void addTemporaryQCPGraph(QCPGraph * graph,const QString objectName)
{
    graph->setObjectName(TemporaryStr + Separator + objectName);
    _QCPGraphVtr.push_back(graph);
}

void confirm()
{
    for(QCPItemText *item:_QCPItemTextVtr){
        objectNameModifyConfirm(item);
    }

    for(QCPItemLine *item:_QCPItemLineVtr){
        objectNameModifyConfirm(item);
    }

    for(QCPGraph *graph:_QCPGraphVtr){
        objectNameModifyConfirm(graph);
    }
}


void removeItem(QObject *obj)
{
    for (int i = _QCPItemTextVtr.size() - 1; i >= 0; --i) {
        QCPItemText *item = _QCPItemTextVtr[i];
        if (item == obj) {

            _QCPItemTextVtr.remove(i);
            //            return;
        }
    }

    for (int i = _QCPItemLineVtr.size() - 1; i >= 0; --i) {
        QCPItemLine *item = _QCPItemLineVtr[i];
        if (item == obj) {
            _QCPItemLineVtr.remove(i);
            //            return;
        }
    }

    for (int i = _QCPGraphVtr.size() - 1; i >= 0; --i) {
        QCPGraph *item = _QCPGraphVtr[i];
        if (item == obj) {
            _QCPGraphVtr.remove(i);
            //            return;
        }
    }

}


void objectNameModifyConfirm(QObject* obj) {

    QString objectName = obj->objectName();

    if (objectName.contains(Separator)) {
        QStringList parts = objectName.split(Separator);

        if (parts.size() >= 2) {
            QString extractedObjectName = parts[1];
            QString newObjectName = ConfirmStr + Separator + extractedObjectName;

            obj->setObjectName(newObjectName);
        }
    }
}

void removeItemsByObjectName(const QString objectName)
{
    for (int i = _QCPItemTextVtr.size() - 1; i >= 0; --i) {
        QCPItemText *item = _QCPItemTextVtr[i];
        if (item->objectName().contains(objectName)){

            _QCPItemTextVtr.remove(i);
        }
    }

    for (int i = _QCPItemLineVtr.size() - 1; i >= 0; --i) {
        QCPItemLine *item = _QCPItemLineVtr[i];
        if (item->objectName().contains(objectName)){
            _QCPItemLineVtr.remove(i);
        }
    }

    for (int i = _QCPGraphVtr.size() - 1; i >= 0; --i) {
        QCPGraph *item = _QCPGraphVtr[i];
        if (item->objectName().contains(objectName)){
            _QCPGraphVtr.remove(i);
        }
    }
}

}
