/* -*- Mode: C++; indent-tabs-mode: nil; tab-width: 4 -*-
 * -*- coding: utf-8 -*-
 *
 * Copyright (C) 2023 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "media-key-settings.h"


#define MEDIAKEY_SCHEMA         "org.ukui.SettingsDaemon.plugins.media-keys"

#define GSETTINGS_INIT_RESULT "gsettings-init-result"   //gsettings初始化结果

MediaKeySettings::MediaKeySettings(QObject *parent) : QObject(parent)
{
    initSettings();
}

MediaKeySettings::~MediaKeySettings()
{
    clearMapData();
}

MediaKeySettings *MediaKeySettings::instance()
{
    static MediaKeySettings MediaKeySettings;
    return &MediaKeySettings;
}

const QStringList MediaKeySettings::getGsettingsKeys()
{
    return m_keysData.keys();
}

QVariant MediaKeySettings::getGsettingsValue( const QString &key)
{
    if (m_keysData.contains(key)) {
        return m_keysData.value(key, QVariant(QVariant::Type::Invalid));
    } else {
        return QVariant(QVariant::Type::Invalid);
    }
}

bool MediaKeySettings::resultInitSettings()
{
    //包含GSETTINGS_INIT_RESULT ，配置初始化失败
    return !m_keysData.contains(GSETTINGS_INIT_RESULT);
}

void MediaKeySettings::resetSettings()
{
    if (m_settings) {
        m_settings.reset();
    }
}

void MediaKeySettings::initSettings()
{
    if (QGSettings::isSchemaInstalled(MEDIAKEY_SCHEMA)) {
        m_settings = GsettingsPtr(new QGSettings(MEDIAKEY_SCHEMA));
        for (const QString& key : m_settings->keys()) {
            m_keysData.insert(key, m_settings->get(key));
        }
        connect(m_settings.data(), SIGNAL(changed(const QString&)), this, SLOT(onKeyChanged(const QString&)), Qt::DirectConnection);
    } else {
        m_keysData.insert(GSETTINGS_INIT_RESULT, false);
    }
}

void MediaKeySettings::clearMapData()
{
    GsettingsMap().swap(m_keysData);
}

//slots
void MediaKeySettings::onKeyChanged(const QString &key)
{
    QVariant value = m_settings->get(key);
    m_keysData.insert(key, value);
    Q_EMIT keyChanged(key, value);
}
