#include "tagpool.h"
#include "dbmanager.h"

// TagPool类的构造函数，用于初始化数据库管理器并连接信号与槽
TagPool::TagPool(DBManager *dbManager, QObject *parent) : QObject(parent), m_dbManager{ dbManager }
{
    connect(
            m_dbManager, &DBManager::nodesTagTreeReceived, this,
            [this](const NodeTagTreeData &treeData) {
                QMap<int, TagData> newPool;
                for (const auto &tag : treeData.tagTreeData) {
                    newPool[tag.id()] = tag;
                }
                setTagPool(newPool);
            },
            Qt::QueuedConnection);
    connect(m_dbManager, &DBManager::tagAdded, this, &TagPool::onTagAdded, Qt::QueuedConnection);
    connect(m_dbManager, &DBManager::tagRemoved, this, &TagPool::onTagDeleted,
            Qt::QueuedConnection);
    connect(m_dbManager, &DBManager::tagRenamed, this, &TagPool::onTagRenamed,
            Qt::QueuedConnection);
    connect(m_dbManager, &DBManager::tagColorChanged, this, &TagPool::onTagColorChanged,
            Qt::QueuedConnection);
}

// 设置标签池的新数据
void TagPool::setTagPool(const QMap<int, TagData> &newPool)
{
    m_pool = newPool;
    emit dataReset();
}

// 删除指定ID的标签
void TagPool::onTagDeleted(int id)
{
    m_pool.remove(id);
    emit tagDeleted(id);
}

// 添加新的标签
void TagPool::onTagAdded(const TagData &tag)
{
    m_pool[tag.id()] = tag;
}

// 重命名指定ID的标签
void TagPool::onTagRenamed(int id, const QString &newName)
{
    m_pool[id].setName(newName);
    emit dataUpdated(id);
}

// 修改指定ID的标签颜色
void TagPool::onTagColorChanged(int id, const QString &newColor)
{
    m_pool[id].setColor(newColor);
    emit dataUpdated(id);
}

// 获取指定ID的标签数据
TagData TagPool::getTag(int id) const
{
    return m_pool[id];
}

// 检查标签池中是否包含指定ID的标签
bool TagPool::contains(int id) const
{
    return m_pool.contains(id);
}

// 获取标签池中所有标签的ID列表
QList<int> TagPool::tagIds() const
{
    return m_pool.keys();
}