#include "global.h"

#include <QDir>
#include <QSettings>
#include <QFileInfo>
#include <QDebug>

Global *Global::Instance()
{
    if (mInstance == nullptr)
    {
        QMutexLocker locker(&mMutex);
        if (mInstance == nullptr)
            mInstance = new Global;
    }
    return mInstance;
}

void Global::setRootDirPath(const QString &path)
{
    mRootPath = path;
    checkResource();
}

QString Global::rootDirPath()
{
    return mRootPath;
}

QString Global::resourceDirPath()
{
    return mRootPath + "/config";
}

void Global::setParam(Param p)
{
    mParam = p;
    QSettings settings(configFilePath(), QSettings::IniFormat);
    settings.setIniCodec("UTF-8");

    QFileInfo iniFileInfo(configFilePath());
    settings.setValue("/Config/DocSetPath", mParam.docSetPath);
}


Param Global::param()
{
    return mParam;
}



QString Global::configFilePath()
{
    return resourceDirPath() + "/SetupConfig.ini";
}

Global::Global()
{
    mRootPath = "";
}

void Global::checkResource()
{
    // 检查配置文件目录是否存在
    QList<QString> listPath;
    listPath << rootDirPath() << resourceDirPath();
    for (QString path : listPath)
    {
        QDir dir(path);
        if (!dir.exists())
            dir.mkpath(path);
    }

    // 定义ini文件处理类
    QSettings settings(configFilePath(), QSettings::IniFormat);
    settings.setIniCodec("UTF-8");

    QFileInfo iniFileInfo(configFilePath());
    if (!iniFileInfo.exists())
    {
        settings.setValue("/Config/DocSetPath", mParam.docSetPath);
    }
    else
    {

        if (!settings.contains("/Config/DocSetPath"))
        {
            settings.setValue("/Config/DocSetPath", mParam.docSetPath);
        }


        mParam.docSetPath = settings.value("/Config/DocSetPath", mParam.docSetPath).toString();
    }
}

Global *Global::mInstance = nullptr;
QMutex Global::mMutex;
Global::GC Global::gc;

