#include "fmp_settings.h"
#include "global.h"
#include "tools.h"
#include "fmglobal.h"
#include <QSettings>
#include <QTextCodec>
#include <QDebug>

/**
 * @brief The FMPSettings class
 */
FMPSettings::FMPSettings(QObject *parent)
    : QObject(parent),
      d_ptr(new FMPSettingsPrivate(parent))
{
}

FMPSettings::~FMPSettings()
{
    if (d_ptr) {
        delete d_ptr;
        d_ptr = nullptr;
    }
}

QVariant FMPSettings::GetValue(const QString &k, QVariant default_val)
{
    Q_D(FMPSettings);

    return d->GetValue(k, default_val);
}

bool FMPSettings::SetValue(const QString &k, QVariant v)
{
    Q_D(FMPSettings);

    return d->SetValue(k, v);
}

QStringList FMPSettings::GetAllKeys(const QString &g)
{
    Q_D(FMPSettings);

    return d->GetAllKeys(g);
}

/**
 ***************************************************************
 */
FMPSettingsPrivate::FMPSettingsPrivate(QObject *parent)
    : QObject(parent),
      _sets(nullptr)
{
    char path[MAX_PATH] = {0};
    ToolS::GetProcPath(path);
    _sets = new QSettings(QString::fromLocal8Bit("%1/%2").arg(path).arg(USERCONFIG_NAME), QSettings::IniFormat);
    _sets->setIniCodec(QTextCodec::codecForName("GB2312"));
}

FMPSettingsPrivate::~FMPSettingsPrivate()
{
    if(_sets!=nullptr) {
        delete _sets;
    }
}

QVariant FMPSettingsPrivate::GetValue(const QString &k, QVariant default_val)
{
    return _sets->value(k, default_val);
}

bool FMPSettingsPrivate::SetValue(const QString &k, QVariant v)
{
    _sets->setValue(k, v);
    return (_sets->value(k) == v);
}

QStringList FMPSettingsPrivate::GetAllKeys(const QString &g)
{
    if(g.isEmpty()) {
        return _sets->allKeys();
    } else {
        _sets->beginGroup(g);
        QStringList keys = _sets->allKeys();
        _sets->endGroup();
        return keys;
    }
}
