/* -*- Mode: C++; indent-tabs-mode: nil; tab-width: 4 -*-
 * -*- coding: utf-8 -*-
 *
 * Copyright (C) 2020 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 <glib.h>
#include <gio/gio.h>

#include <QDebug>
#include <QString>
#include "qconftype.h"
#include "ukui-qgsettings.h"

struct QGSettingsPrivate
{
    QByteArray          path;
    GSettingsSchema     *schema;
    QByteArray          schemaId;
    GSettings           *settings;
    gulong              signalHandlerId;

    static void settingChanged(GSettings *settings, const gchar *key, gpointer userData);
};

void QGSettingsPrivate::settingChanged(GSettings *, const gchar *key, gpointer userData)
{
    UKUIGSettings *self = (UKUIGSettings *)userData;

    /**
     * 这里不属于 QObject的子类，只能通过此方法强制调用 QObject 子类的方法或信号
     *
     * Qt::QueuedConnection         发送一个QEvent，并在应用程序进入主事件循环后立即调用该成员。
     * Qt::DirectConnection         立即调用
     * Qt::BlockingQueuedConnection 则将以与Qt::QueuedConnection相同的方式调用该方法，除了当前线程将阻塞直到事件被传递。使用此连接类型在同一线程中的对象之间进行通信将导致死锁
     * Qt::AutoConnection           则如果obj与调用者位于同一个线程中，则会同步调用该成员; 否则它将异步调用该成员
     *
     */
    QMetaObject::invokeMethod(self, "changed", Qt::AutoConnection, Q_ARG(QString, key));
}

static bool is_item_in_schema (const gchar* const* items, const QByteArray & item)
{
    while (*items) {
       if (g_strcmp0 (*items++, item) == 0) {
           return true;
       }
    }
    return false;
}

UKUIGSettings::UKUIGSettings(const QByteArray &schemaId, const QByteArray &path, QObject *parent) : QObject(parent)
{
    mPriv = new QGSettingsPrivate;
    mPriv->schemaId = schemaId;
    mPriv->path = path;

    if (false == is_item_in_schema (g_settings_list_schemas(), schemaId)){
        mPriv->settings = nullptr;
        return;
    }

    if (mPriv->path.isEmpty()) {
        mPriv->settings = g_settings_new(mPriv->schemaId.constData());
    } else {
        mPriv->settings = g_settings_new_with_path(mPriv->schemaId.constData(), mPriv->path.constData());
    }
    g_object_get(mPriv->settings, "settings-schema", &mPriv->schema, NULL);
    mPriv->signalHandlerId = g_signal_connect(mPriv->settings, "changed", G_CALLBACK(QGSettingsPrivate::settingChanged), this);
}

UKUIGSettings::~UKUIGSettings()
{
    if (mPriv->schema) {
        g_settings_sync ();
        g_signal_handler_disconnect(mPriv->settings, mPriv->signalHandlerId);
        g_object_unref (mPriv->settings);
        g_settings_schema_unref (mPriv->schema);
    }
    delete mPriv;
}

QVariant UKUIGSettings::get(const QString &key) const
{
    gchar *gkey = unqtify_name(key);
    if (mPriv->settings == nullptr) {
        return -1;
    }

    if (!keys().contains(gkey)) {
        qWarning() << QString("can't find int key:%1 in %2" ).arg(key).arg(mPriv->schemaId.data());
        return QVariant(0);
    }

    GVariant *value = g_settings_get_value(mPriv->settings, gkey);
    if( NULL == value) {
        qWarning() << "g_settings_get_value is faild";
        return QVariant(0);
    }
    QVariant qvalue = qconf_types_to_qvariant(value);
    g_variant_unref(value);
    g_free(gkey);

    return qvalue;
}

void UKUIGSettings::set(const QString &key, const QVariant &value)
{
    if (mPriv->settings == nullptr) {
        return;
    }
    gchar *gkey = unqtify_name(key);
    if (keys().contains(gkey)) {
        if (!trySet(key, value)) {

        }
//            qWarning() << QString("can't find int key:%1 in %2" ).arg(key).arg(value);
    } else {
//        qWarning() << QString("can't find int key:%1 in %2" ).arg(key).arg(mPriv->schemaId.data());
    }
}

bool UKUIGSettings::trySet(const QString &key, const QVariant &value)
{
    gchar *gkey = unqtify_name(key);
    bool success = false;


    /* fetch current value to find out the exact type */
    GVariant *cur = g_settings_get_value(mPriv->settings, gkey);
    GVariant *new_value = qconf_types_collect_from_variant(g_variant_get_type (cur), value);
    if (new_value)
        success = g_settings_set_value(mPriv->settings, gkey, new_value);

    g_free(gkey);
    g_variant_unref (cur);

    return success;
}

void UKUIGSettings::setEnum(const QString& key,int value)
{
    if (mPriv->settings == nullptr) {
        return ;
    }
    g_settings_set_enum (mPriv->settings,key.toLatin1().data(),value);
}

int UKUIGSettings::getEnum(const QString& key)
{
    int enumNum;
    if (mPriv->settings == nullptr) {
        return -1;
    }
    enumNum = g_settings_get_enum (mPriv->settings,key.toLatin1().data());
    return enumNum;
}

char **UKUIGSettings::getStrv(const QString& key)
{
    return g_settings_get_strv(mPriv->settings,key.toLatin1().data());
}

void UKUIGSettings::delay()
{
    g_settings_delay(mPriv->settings);
}

void UKUIGSettings::apply()
{
    g_settings_apply(mPriv->settings);
}

QStringList UKUIGSettings::keys() const
{
    QStringList list;
    //gchar **keys = g_settings_list_keys(mPriv->settings);
    gchar **keys = g_settings_schema_list_keys(mPriv->schema);
    for (int i = 0; keys[i]; i++)
        list.append(keys[i]);
//    list.append(qtify_name(keys[i]));

    g_strfreev(keys);

    return list;
}

QVariantList UKUIGSettings::choices(const QString &qkey) const
{
    gchar *key = unqtify_name (qkey);
    GSettingsSchemaKey *schema_key = g_settings_schema_get_key (mPriv->schema, key);
    GVariant *range = g_settings_schema_key_get_range(schema_key);
    g_settings_schema_key_unref (schema_key);
    g_free(key);

    if (range == NULL)
        return QVariantList();

    const gchar *type;
    GVariant *value;
    g_variant_get(range, "(&sv)", &type, &value);

    QVariantList choices;
    if (g_str_equal(type, "enum")) {
        GVariantIter iter;
        GVariant *child;

        g_variant_iter_init (&iter, value);
        while ((child = g_variant_iter_next_value(&iter))) {
            choices.append(qconf_types_to_qvariant(child));
            g_variant_unref(child);
        }
    }

    g_variant_unref (value);
    g_variant_unref (range);

    return choices;
}

void UKUIGSettings::reset(const QString &qkey)
{
    gchar *key = unqtify_name(qkey);
    g_settings_reset(mPriv->settings, key);
    g_free(key);
}

bool UKUIGSettings::isSchemaInstalled(const QByteArray &schemaId)
{
    GSettingsSchemaSource *source = g_settings_schema_source_get_default ();
    GSettingsSchema *schema = g_settings_schema_source_lookup (source, schemaId.constData(), TRUE);
    if (schema) {
        g_settings_schema_unref (schema);
        return true;
    } else {
        return false;
    }
}

QStringList UKUIGSettings::getAllSchemaWithFilter(const QByteArray &filter)
{
    QStringList ret;
    const gchar* const* items = g_settings_list_schemas();

    while (*items) {
       if (strncmp (*items, filter, filter.count()) == 0) {
           ret.append(QString(*items));
       }
       *items++;
    }

    return ret;
}

QString UKUIGSettings::getSummary(const QString &key) const
{
    gchar* gKey = unqtify_name(key);
    if (!keys().contains(gKey)) {
        qWarning() << QString("can't find int key:%1 in %2" ).arg(key).arg(mPriv->schemaId.data());
        g_free(gKey);
        return QString();
    }

    GSettingsSchemaKey *schemaKey = nullptr;
    schemaKey = g_settings_schema_get_key(mPriv->schema, gKey);

    if (!schemaKey) {
        qWarning() << QString("can't find int key:%1 in %2" ).arg(key).arg(mPriv->schemaId.data());
        g_free(gKey);
        return QString();
    }
    g_free(gKey);

    const gchar* gSummary = g_settings_schema_key_get_summary(schemaKey);
    g_settings_schema_key_unref(schemaKey);
    return QString(gSummary);
}

QString UKUIGSettings::getKeyType(const QString &key) const
{
    QString ret = "";
    gchar* gKey = unqtify_name(key);
    if (!keys().contains(gKey)) {
        qWarning() << QString("can't find int key:%1 in %2" ).arg(key).arg(mPriv->schemaId.data());
        g_free(gKey);
        return QString();
    }
    GVariant *cur = g_settings_get_value(mPriv->settings, gKey);
    ret = g_variant_get_type_string(cur);
    g_free(gKey);
    return ret;
}
