#include "aibarconfig.h"

#include <QFileInfo>
#include <QSettings>
#include <QStandardPaths>
#include <QGuiApplication>
#include <QDir>

namespace uos_ai {
class AiBarConfigGlobal : public AiBarConfig {};
Q_GLOBAL_STATIC(AiBarConfigGlobal, configerGlobal)
}

using namespace uos_ai;

AiBarConfig *AiBarConfig::instance()
{
    return configerGlobal;
}

AiBarConfig::AiBarConfig(QObject *parent)
    : QObject{parent}
{
    init();
}

void AiBarConfig::onFileChanged(const QString &path)
{
    qDebug() << "config-file changed" << path;
    delayLoad.start();
}

void AiBarConfig::onLoadConfig()
{
    QSettings set(configFilePath, QSettings::IniFormat);
    if (set.status() != QSettings::NoError) {
        qWarning() << "config file error" << set.status();
        return;
    }

    set.beginGroup("AiBar");
    enableFileDrag = set.value("enableFileDrag", true).toBool();
    qDebug() << "Ai Bar enableFileDrag: " << enableFileDrag;
    set.endGroup();
}

void AiBarConfig::init()
{
    auto configPath = QStandardPaths::standardLocations(QStandardPaths::ConfigLocation).first();
    configPath = configPath
                 + "/" + qApp->organizationName()
                 + "/uos-ai-assistant/uos-ai-assistant" + ".conf";

    QFileInfo configFile(configPath);
    if (!configFile.exists()) {
        configFile.absoluteDir().mkpath(".");

        //生成文件
        QFile file(configPath);
        file.open(QFile::NewOnly);
        file.close();
        qInfo() << "create conf " << configPath;
    }

    configFilePath = configFile.absoluteFilePath();

    watcher = new QFileSystemWatcher(this);
    watcher->addPath(configFile.absolutePath());
    watcher->addPath(configFile.absoluteFilePath());
    connect(watcher, &QFileSystemWatcher::fileChanged, this, &AiBarConfig::onFileChanged);
    connect(watcher, &QFileSystemWatcher::directoryChanged, this, &AiBarConfig::onFileChanged);

    delayLoad.setSingleShot(true);
    delayLoad.setInterval(50);
    connect(&delayLoad, &QTimer::timeout, this, &AiBarConfig::onLoadConfig);

    onLoadConfig();
}
