#include "projectmanager.h"
#include "logger.h"

ProjectManager::ProjectManager(QObject *parent)
    : QObject{parent}
    , m_xmlDocPtr(nullptr)
{

}

ProjectManager::~ProjectManager()
{
    closeProject();
}

bool ProjectManager::openProject(const QString &fileName)
{
    // 指定编码（如UTF-8）
    m_xmlDocPtr = xmlReadFile(fileName.toUtf8().data(), "UTF-8", XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING);
    if (m_xmlDocPtr == NULL) {
        LOG_ERROR("invalid monitor xml: {}", fileName.toUtf8().data());
        return false;
    }

    // 获取根节点
    xmlNodePtr projectNodePtr = xmlDocGetRootElement(m_xmlDocPtr);
    if (projectNodePtr == NULL) {
        LOG_INFO("empty monitor xml: {}", fileName.toUtf8().data());
        xmlFreeDoc(m_xmlDocPtr);
        return false;
    }

    if (xmlStrcmp(projectNodePtr->name, BAD_CAST "project") != 0) {
        LOG_ERROR("error project node, node name is: {}", (char *)projectNodePtr->name);
        xmlFreeDoc(m_xmlDocPtr);
        return false;
    }

    xmlNodePtr canvasNodePtr = projectNodePtr->children;
    while(canvasNodePtr)
    {
        if (canvasNodePtr->type == XML_ELEMENT_NODE && xmlStrcmp(canvasNodePtr->name, BAD_CAST "canvas") == 0)
        {
            m_canvasList.push_back(canvasNodePtr);
        }
        canvasNodePtr = canvasNodePtr->next;
    }
    return true;
}

void ProjectManager::closeProject()
{
    if(m_xmlDocPtr)
    {
        // 释放资源
        xmlFreeDoc(m_xmlDocPtr);
        xmlCleanupParser();
        m_xmlDocPtr = nullptr;
        m_canvasList.clear();
    }
}

xmlNodePtr ProjectManager::canvas(const int &index)
{
    if(index < 0 || index >= m_canvasList.count())
        return nullptr;
    return m_canvasList[index];
}

int ProjectManager::canvasCount() const
{
    return m_canvasList.count();
}
