/* -*- 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 "rfkill-state.h"
#include "rfkillswitch.h"
#include "clib-syslog.h"

#include <QDebug>

#define MEDIA_SCHEMA   "org.ukui.SettingsDaemon.plugins.media-keys-state"
static QString s_rfkillState = "rfkill-state";

Q_GLOBAL_STATIC(RfkillState, s_rfkill)

RfkillState::RfkillState(QObject *parent) : QObject(parent)
{

}

RfkillState::~RfkillState()
{
    if (m_rfkillSettings) {
        disconnect(m_rfkillSettings,SIGNAL(changed(QString)),  this, SLOT(doSettingsChangeAction(const QString&)));
        m_rfkillSettings->deleteLater();
        m_rfkillSettings = nullptr;
    }
}

RfkillState *RfkillState::self()
{
    return s_rfkill;
}

void RfkillState::initialization()
{
    if (QGSettings::isSchemaInstalled(QByteArray(MEDIA_SCHEMA))) {
        if (!m_rfkillSettings) {
            m_rfkillSettings = new QGSettings(MEDIA_SCHEMA);
        }
        connect(m_rfkillSettings, SIGNAL(changed(QString)),  this, SLOT(doSettingsChangeAction(const QString&)));

        //此改动用于rfkill（飞行模式）的全局配置
        {
            //读取到全局配置，不再读取gsettings值
            QVariant state = getGlobalRfkillState();
            if (state.isValid()) {
                setFlightState(state.toInt());
                if (m_rfkillSettings) {
                    m_rfkillSettings->set(s_rfkillState, state.toInt());
                }
            } else if (m_rfkillSettings->keys().contains(s_rfkillState)) {
                //考虑到升级，启动时，未读取到全局配置，从gsettings读取，同步到全局配置
                int state = m_rfkillSettings->get(s_rfkillState).toInt();
                if(state >= 0) {
                    if(-1 == getFlightState()) {
                        m_rfkillSettings->set(s_rfkillState, -1);
                    } else {
                        if (state) {
                            setFlightState(state);
                            setGlobalRfkillState(state);
                        }
                    }
                }
            }
        }
    }
    // 用户状态切换信号
    QDBusConnection::sessionBus().connect(QString(),\
                                          QStringLiteral("/GlobaSignal"),\
                                          QStringLiteral("org.ukui.SettingsDaemon.GlobalSignal"),\
                                          "Active", this, SLOT(onUserActive(bool)));
}

int RfkillState::getWlanState()
{
    return RfkillSwitch::instance()->getCurrentWlanMode();
}

void RfkillState::setWlanState(bool state)
{
    Q_UNUSED(state)
    RfkillSwitch::instance()->turnWifiOn();
}

int RfkillState::getFlightState()
{
    return RfkillSwitch::instance()->getCurrentFlightMode();
}

void RfkillState::setFlightState(bool state)
{
    RfkillSwitch::instance()->toggleFlightMode(state);
}

int RfkillState::getBluetooth()
{
    return RfkillSwitch::instance()->getCurrentBluetoothMode();
}

void RfkillState::setBluetooth(bool state)
{
    RfkillSwitch::instance()->toggleBluetoothMode(state);
}

void RfkillState::setSettingsState(bool state)
{
    if (m_rfkillSettings && m_rfkillSettings->keys().contains(s_rfkillState)) {
        m_rfkillSettings->set(s_rfkillState, state);
    }
}

void RfkillState::setGlobalRfkillState(const QVariant& state)
{
    QDBusInterface globalManager("com.settings.daemon.qt.systemdbus", \
                                 "/globalconfig", \
                                 "com.settings.daemon.interface", \
                                 QDBusConnection::systemBus());
    QList<QVariant> arguments;
    arguments << QVariant(QString::fromLatin1("rfkill")) << QVariant(QString::fromLatin1("rfkill")) << QVariant::fromValue(QDBusVariant(state));
    globalManager.asyncCallWithArgumentList("setGlobalConf", arguments);
}

QVariant RfkillState::getGlobalRfkillState()
{
    QDBusInterface globalManager("com.settings.daemon.qt.systemdbus", \
                          "/globalconfig", \
                          "com.settings.daemon.interface", \
                          QDBusConnection::systemBus());

    QDBusReply<QVariant> reply = globalManager.call(QStringLiteral("getGlobalConf"), QStringLiteral("rfkill"), QStringLiteral("rfkill"));

    if (reply.isValid()) {
        return reply.value();
    }
    USD_LOG(LOG_ERR,"globalManager dbus interface failed .");
    return QVariant(QVariant::Invalid);
}

void RfkillState::doSettingsChangeAction(const QString &key)
{
    if (key == s_rfkillState) {
        int state = m_rfkillSettings->get(s_rfkillState).toInt();
        if(state != -1) {
            setFlightState(state);
            setGlobalRfkillState(state);
        }
    }
}

void RfkillState::onUserActive(bool state)
{
    //用户登录状态改变，获取全局配置，设置飞行模式状态
    if (state) {
        QVariant state = getGlobalRfkillState();
        if (state.isValid()) {
            m_rfkillSettings->set(s_rfkillState, state);
        }
    }
}
