/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 *
 * Copyright (C) 2019 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 2 of the License, or
 * (at your option) 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, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */
#include "getshortcutworker.h"
#include <QDebug>
#include <QDBusReply>
#include "../../universalinterface.h"
#include "type.h"

GetShortcutWorker::GetShortcutWorker(QObject *parent)
    : QThread(parent) {

}

GetShortcutWorker::~GetShortcutWorker() {

}

void GetShortcutWorker::getWindowShortcut() {
    QDBusInterface* kwinInterface = UniversalInterface::self()->kwinDbusInterface();
    if (!kwinInterface || !kwinInterface->isValid()) {
        qDebug() << Q_FUNC_INFO << "kwin interface failed";
        return;
    }
    QDBusReply<QVariantList> res = kwinInterface->call("getShortcutInfos");
    const static int WIN_SHORTCUT_MIN_LEN = 3;
    const static int WIN_SHORTCUT_MAX_LEN = 4;
    qDebug() << Q_FUNC_INFO << "window shortcut size" << res.value().size();
    for (auto &shortcutInfo : res.value()) {
        QStringList kwinStringList = shortcutInfo.toStringList();
        int size = kwinStringList.size();

        if (size < WIN_SHORTCUT_MIN_LEN) {
            continue;
        }
        QString key = kwinStringList.at(0);
        QString name = kwinStringList.at(1);
        for (int index = 2; index < size && index < WIN_SHORTCUT_MAX_LEN; ++index) {
            QString value = kwinStringList.at(index);
            if (index == WIN_SHORTCUT_MIN_LEN) {
                key = key + "2";
            }
//            qDebug() << Q_FUNC_INFO << "window shortcut" << name << key << value;
            emit windowShortcutGenerate(name, key, value);
        }
    }
}

void GetShortcutWorker::getSystemShortcut() {
    GSettings *desktopsettings = nullptr;
    if (QGSettings::isSchemaInstalled(KEYBINDINGS_DESKTOP_SCHEMA)) {
        desktopsettings = g_settings_new(KEYBINDINGS_DESKTOP_SCHEMA);
        char **dkeys = g_settings_list_keys(desktopsettings);
        for (int i = 0; dkeys[i] != nullptr; i++) {
            // 跳过非快捷键
            if (!g_strcmp0(dkeys[i], "active") || !g_strcmp0(dkeys[i], "volume-step")
                || !g_strcmp0(dkeys[i], "priority") || !g_strcmp0(dkeys[i], "enable-osd")) {
                continue;
            }

            GVariant *variant = g_settings_get_value(desktopsettings, dkeys[i]);
            gsize size = g_variant_get_size(variant);
            char *str   = const_cast<char *>(g_variant_get_string(variant, &size));

            // 保存桌面快捷键
            QString key = QString(dkeys[i]);
            QString value = QString(str);
            if (value.contains("KP_Delete")) {
                value = "<Ctrl><Alt>Del";
                Q_EMIT generalShortcutGenerate(KEYBINDINGS_DESKTOP_SCHEMA, key, value);
            }
            if (value != "" && !value.contains("XF86") && !value.contains("KP_")) {
                Q_EMIT generalShortcutGenerate(KEYBINDINGS_DESKTOP_SCHEMA, key, value);
            }
        }
        g_strfreev(dkeys);
        g_object_unref(desktopsettings);
    }
}

void GetShortcutWorker::getCustomShortcut() {
    QList<char *> existsPath = listExistsCustomShortcutPath();
    for (char *path : existsPath) {
        QString strFullPath = QString(KEYBINDINGS_CUSTOM_DIR);
        strFullPath.append(path);

        const QByteArray ba(KEYBINDINGS_CUSTOM_SCHEMA);
        const QByteArray bba(strFullPath.toLatin1().data());
        QGSettings settings(ba, bba);
        QString pathStr = strFullPath;
        QString actionStr = settings.get(ACTION_KEY).toString();
        QString bindingStr = settings.get(BINDING_KEY).toString();
        QString nameStr = settings.get(NAME_KEY).toString();
        Q_EMIT customShortcutGenerate(pathStr, nameStr, bindingStr, actionStr);
    }
}

void GetShortcutWorker::run() {
    // get window shortcut
    getWindowShortcut();

    // get desktop shortcut
    getSystemShortcut();

    // get custdom shortcut
    getCustomShortcut();

    Q_EMIT workerComplete();
}

QList<char *> GetShortcutWorker::listExistsCustomShortcutPath() {
    char ** childs;
    int len;

    DConfClient * client = dconf_client_new();
    childs = dconf_client_list (client, KEYBINDINGS_CUSTOM_DIR, &len);
    g_object_unref (client);

    QList<char *> vals;

    for (int i = 0; childs[i] != nullptr; i++){
        if (dconf_is_rel_dir (childs[i], nullptr)){
            char * val = g_strdup (childs[i]);

            vals.append(val);
        }
    }
    g_strfreev (childs);
    return vals;
}
