#include "fmp_settings.h"
#include <QSettings>
#include <fmp_logger_i.h>
#include <ctkServiceReference.h>
#include <ctkPluginContext.h>
#include <QDebug>


/**
 * @brief The FMPSettings class
 */
FMPSettings::FMPSettings(ctkPluginContext *context)
    : d_ptr(new FMPSettingsPrivate(context))
{
    StartService();
}

int FMPSettings::StartService()
{
    return d_func()->DoStartService();
}

int FMPSettings::StopService()
{
    return d_func()->DoStopService();
}

int FMPSettings::PostEvent(const QString &topic, const FMPProps &pps)
{
    return FMP_SUCCESS;
}


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

    return d->GetValue(k);
}

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

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

/**
 ***************************************************************
 */
FMPSettingsPrivate::FMPSettingsPrivate(ctkPluginContext *ctx)
    : _ctx(ctx),
      _sets(0)
{
}

int FMPSettingsPrivate::DoStartService()
{
    if (!_sets) {
        _sets = new QSettings(_ctx->getProperty(FMP_PROPKEY_CFG).toString(), QSettings::IniFormat);
    }

    return FMP_SUCCESS;
}

int FMPSettingsPrivate::DoStopService()
{
    if (_sets) {
        delete _sets;
        _sets = 0;
    }

    return FMP_SUCCESS;
}

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

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