/*
 * Copyright (C) 2022, 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
 * (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, see <https://www.gnu.org/licenses/>.
 *
 */

#include "wifi-dbus-query.h"
#include <QProcess>
#include <QDBusReply>
#include <QDBusInterface>
#include <QApplication>
#include <QTranslator>
#include <QDebug>

WifiDbusQuery::WifiDbusQuery(QObject *parent) : QObject(parent)
{

}

void WifiDbusQuery::isWirelessDeviceEnabled()
{
    m_isWirelessDeviceEnable = false;

    QDBusInterface interface( NETWORK_MANAGER_NAME,
                              NETWORK_MANAGER_PATH,
                              NETWORK_MANAGER_INTERFACE,
                              QDBusConnection::systemBus() );

    if (interface.isValid()) {

        QDBusMessage reply = interface.call("GetAllDevices");

        if (!reply.arguments().isEmpty()) {
            QDBusArgument devices = reply.arguments().at(0).value<QDBusArgument>();
            QDBusObjectPath devicePath;
            devices.beginArray();
            while (!devices.atEnd()) {
                devices >> devicePath;
                QDBusInterface deviceInterface(NETWORK_MANAGER_NAME, devicePath.path(),
                                                 "org.freedesktop.DBus.Properties", QDBusConnection::systemBus());

                QDBusReply<QVariant> retMsg = deviceInterface.call("Get", "org.freedesktop.NetworkManager.Device","DeviceType");

                if (!retMsg.isValid()) {
                    continue;
                }

                if (retMsg.value() == 2) {
                    m_isWirelessDeviceEnable = true;
                }
            }
        }
    }

    Q_EMIT deviceQuery(m_isWirelessDeviceEnable);
}

void WifiDbusQuery::queryUsedWifiConnect(QDBusInterface *networkDbusInterface)
{
    if (networkDbusInterface != nullptr) {
        QString wifiName;
        QDBusMessage result = networkDbusInterface->call("Get", NETWORK_MANAGER_INTERFACE, "ActiveConnections");
        QList<QVariant> outArgs = result.arguments();

        if (!outArgs.isEmpty()) {
            QVariant first = outArgs.at(0);

            if (first.isValid()) {
                QDBusVariant dbvFirst = first.value<QDBusVariant>();
                QVariant vFirst = dbvFirst.variant();

                if (vFirst.isValid()) {
                    QDBusArgument dbusArgs = vFirst.value<QDBusArgument>();
                    QDBusObjectPath objPath;
                    dbusArgs.beginArray();
                    while (!dbusArgs.atEnd()) {
                        dbusArgs >> objPath;
                        QDBusInterface interface( NETWORK_MANAGER_NAME,
                                                  objPath.path(),
                                                  "org.freedesktop.DBus.Properties",
                                                  QDBusConnection::systemBus() );

                        QDBusReply<QVariant> replyState = interface.call("Get", "org.freedesktop.NetworkManager.Connection.Active", "State");

                        if (!replyState.isValid()) {
                            continue;
                        }

                        if(replyState.value().toInt() == 1) {
                            QDBusConnection::systemBus().connect( NETWORK_MANAGER_NAME,
                                                                  objPath.path(),
                                                                  "org.freedesktop.DBus.Properties",
                                                                  "PropertiesChanged", this, SLOT(onPropertiesChanged(QString, QVariantMap)));
                        } else if (replyState.value().toInt() == 2) {
                            QDBusConnection::systemBus().disconnect( NETWORK_MANAGER_NAME,
                                                                     objPath.path(),
                                                                     "org.freedesktop.DBus.Properties",
                                                                     "PropertiesChanged", this, SLOT(onPropertiesChanged(QString, QVariantMap)));

                            QDBusReply<QVariant> replyType = interface.call("Get", "org.freedesktop.NetworkManager.Connection.Active", "Type");

                            if (replyType.isValid()) {
                                QDBusReply<QVariant> replyId = interface.call("Get", "org.freedesktop.NetworkManager.Connection.Active", "Id");
                                if (replyId.isValid()) {
                                    if (replyType.value().toString() == "802-3-ethernet") {
                                        continue;
                                    } else if (replyType.value().toString() == "802-11-wireless" ) {
                                        wifiName = replyId.value().toString();
                                        break;
                                    }
                                }
                            }
                        } else {
                            continue;
                        }
                    }
                    Q_EMIT usedWifiName(wifiName);
                }
            }
        }

    } else {
        qWarning()<<"netWorkdbus is failed,return false";
    }
}

void WifiDbusQuery::onPropertiesChanged(const QString &interface, const QVariantMap &propertyContent)
{
    if (propertyContent.keys().contains("State")) {
        if (propertyContent.value("State").toInt() == 2) {
            Q_EMIT updateState();
        }
    }
}
