#include "globalsettings.h"
#include "defs.h"

#include <QSettings>

QJsonValue variantToJsonValue(const QVariant &value)
{
    // 自动转换常见类型
    switch (value.type()) {
    case QVariant::Bool:
        return QJsonValue(value.toBool());
    case QVariant::Int:
    case QVariant::LongLong:
        return QJsonValue(value.toLongLong());
    case QVariant::Double:
        return QJsonValue(value.toDouble());
    default:
        return QJsonValue(value.toString());
    }
}

GlobalSettings::GlobalSettings(QObject *parent)
    : QObject{parent}
{
    QSettings settings(GLOBAL_SETTINGS_FILE, QSettings::IniFormat);
    settings.setIniCodec("UTF-8");


    for (const QString &group : settings.childGroups()) {
        settings.beginGroup(group);

        QJsonObject groupObj;
        for (const QString &key : settings.childKeys()) {
            QVariant value = settings.value(key);
            groupObj.insert(key, variantToJsonValue(value));
        }

        settings.endGroup();
        m_globalSettings.insert(group, groupObj);
    }
}

GlobalSettings::~GlobalSettings()
{

}

QVariant GlobalSettings::value(const QString &group, const QString &key)
{
    QVariant value;

    if (!m_globalSettings.contains(group) || !m_globalSettings.value(group).isObject())
        return value;

    QJsonObject groupObj = m_globalSettings.value(group).toObject();

    if (!groupObj.contains(key))
        return value;

    return groupObj.value(key).toVariant();
}

void GlobalSettings::setValue(const QString &group, const QString &key, const QVariant &value)
{
    QJsonObject groupObj;

    // 如果 group 已存在且是 object，取出来
    if (m_globalSettings.contains(group) &&
        m_globalSettings.value(group).isObject())
    {
        groupObj = m_globalSettings.value(group).toObject();
    }

    // 设置 / 覆盖 key
    groupObj.insert(key, QJsonValue::fromVariant(value));

    // 写回 group
    m_globalSettings.insert(group, groupObj);

    QSettings settings(GLOBAL_SETTINGS_FILE, QSettings::IniFormat);
    settings.setIniCodec("UTF-8");
    settings.beginGroup(group);
    settings.setValue(key, value);
    settings.endGroup();
}