/*
 * Copyright 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 (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 "daemondbusinterface.h"
#include "loghelper.h"
#include "misc.h"
#include <QApplication>
#include <QDBusConnection>
#include <QDBusPendingCall>
#include <QDBusPendingCallWatcher>
#include <QDBusPendingReply>
#include <QDBusReply>
#include <QDebug>
#include <iostream>

namespace
{

const char *daemon_dbus_service = "com.kylin.ProcessManagerDaemon";
const char *daemon_dbus_path = "/com/kylin/ProcessManagerDaemon";
const char *daemon_dbus_interface = "com.kylin.ProcessManagerDaemon";

}

DaemonDbusInterface::DaemonDbusInterface(QObject *parent)
    : QObject(parent)
    , dbusInterface(daemon_dbus_service, daemon_dbus_path,
                    daemon_dbus_interface, QDBusConnection::systemBus())
{
    connect(&dbusInterface, SIGNAL(ResourceThresholdWarning(QString, int)),
            this, SLOT(onResourceWarning(QString, int)));
}

void DaemonDbusInterface::onResourceWarning(const QString &resource, int level)
{
    qDebug() << "Get resource warning:" << resource << "warning level:" << level;
    Q_EMIT ResourceThresholdWarning(resource.toStdString(), level);
}

void DaemonDbusInterface::createProcessGroup(
    const std::string &path, const std::vector<std::string> &controllers,
    const std::vector<int> &pids)
{
    qDebug() << "DaemonDbusInterface::createProcessGroup: "
             << QString::fromStdString(path)
             << misc::stl2qt::vectorString2QStringList(controllers) << pids.size();

    QList<QVariant> argumentList;
    argumentList
        << QVariant::fromValue(QString::fromStdString(path))
        << QVariant::fromValue(misc::stl2qt::vectorString2QStringList(controllers))
        << QVariant::fromValue(misc::stl2qt::vector2QList<int>(pids));
    asyncCallWithArgumentList("CreateProcessGroup", argumentList);
}

void DaemonDbusInterface::moveProcessToGroup(
    const std::string &path, const std::vector<std::string> &controllers,
    const std::vector<int> &pids)
{
    qDebug() << "DaemonDbusInterface::moveProcessesToGroup: "
             << QString::fromStdString(path)
             << misc::stl2qt::vectorString2QStringList(controllers) << pids.size();

    QList<QVariant> argumentList;
    argumentList
        << QVariant::fromValue(QString::fromStdString(path))
        << QVariant::fromValue(misc::stl2qt::vectorString2QStringList(controllers))
        << QVariant::fromValue(misc::stl2qt::vector2QList<int>(pids));
    asyncCallWithArgumentList("MoveProcessToGroup", argumentList);
}

void DaemonDbusInterface::moveProcessGroupToRoot(const std::string &path, 
    const std::vector<std::string> &controllers)
{
    qDebug() << "DaemonDbusInterface::moveProcessGroupToRoot: "
    << QString::fromStdString(path)
    << misc::stl2qt::vectorString2QStringList(controllers);

    QList<QVariant> argumentList;
    argumentList
        << QVariant::fromValue(QString::fromStdString(path))
        << misc::stl2qt::vectorString2QStringList(controllers);
    asyncCallWithArgumentList("MoveProcessGroupToRoot", argumentList);
}

void DaemonDbusInterface::removeProcessGroup(
    const std::string &path, bool recursive, bool ignoreMigration)
{
    qDebug() << "DaemonDbusInterface::removeProcessGroup: "
        << QString::fromStdString(path)
        << recursive << ignoreMigration;

    QList<QVariant> argumentList;
    argumentList
        << QVariant::fromValue(QString::fromStdString(path))
        << QVariant::fromValue(recursive)
        << QVariant::fromValue(ignoreMigration);
    asyncCallWithArgumentList("RemoveProcessCGroup", argumentList);
}

void DaemonDbusInterface::setProcessGroupResourceLimit(
    const std::string &path, const std::string &controller,
    const std::string &file, const std::string &value)
{
    qDebug() << "DaemonDbusInterface::setProcessGroupResourceLimit: "
             << QString::fromStdString(path)
             << QString::fromStdString(controller)
             << QString::fromStdString(file)
             << QString::fromStdString(value);

    QList<QVariant> argumentList;
    argumentList
        << QVariant::fromValue(QString::fromStdString(path))
        << QVariant::fromValue(QString::fromStdString(controller))
        << QVariant::fromValue(QString::fromStdString(file))
        << QVariant::fromValue(QString::fromStdString(value));
    asyncCallWithArgumentList("SetProcessGroupResourceLimit", argumentList);
}

void DaemonDbusInterface::setSystemdUnitPropertyEnabled(
    const std::string &unitName, const std::string &propertyName, bool enabled)
{
    qDebug() << "DaemonDbusInterface::setSystemdUnitPropertyEnabled: "
             << QString::fromStdString(unitName)
             << QString::fromStdString(propertyName)
             << enabled;
    QList<QVariant> argumentList;
    argumentList
        << QVariant::fromValue(QString::fromStdString(unitName))
        << QVariant::fromValue(QString::fromStdString(propertyName))
        << QVariant::fromValue(enabled);
    asyncCallWithArgumentList("SetSystemdUnitPropertyEnabled", argumentList);
}

double DaemonDbusInterface::getCpuEnergyConsumption()
{
    QDBusPendingReply<double> reply = callWithArgumentList("GetCpuEnergyConsumption", {});
    if (!reply.isValid()) {
        qWarning() << "GetCpuEnergyConsumption failed: " << reply.error();
        return 0;
    }
    return reply.value();
}

void DaemonDbusInterface::reclaimProcesses(const std::vector<int> &pids)
{
    qDebug() << "DaemonDbusInterface::reclaimProcesses: " << misc::stl2qt::vector2QList<int>(pids);

    QList<QVariant> argumentList = {QVariant::fromValue(misc::stl2qt::vector2QList<int>(pids))};
    asyncCallWithArgumentList("ReclaimProcesses", argumentList);
}

void DaemonDbusInterface::reclaimProcessGroups(const std::vector<std::string> &groupNames)
{
    qDebug() << "DaemonDbusInterface::reclaimProcesses: " << misc::stl2qt::vectorString2QStringList(groupNames);

    QList<QVariant> argumentList = {QVariant::fromValue(misc::stl2qt::vectorString2QStringList(groupNames))};
    asyncCallWithArgumentList("ReclaimProcessGroups", argumentList);
}

void DaemonDbusInterface::asyncCallWithArgumentList(const QString &method, const QList<QVariant> &args)
{
    QDBusPendingCall pcall = dbusInterface.asyncCallWithArgumentList(method, args);
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pcall);
    QObject::connect(watcher, &QDBusPendingCallWatcher::finished, qApp,
                     [watcher, method](QDBusPendingCallWatcher *call) {
        QDBusPendingReply<> reply = *call;
        if (reply.isError()) {
            qWarning() << QString("Call daemon dbus %1 error: ").arg(method) << reply.error();
        }
        call->deleteLater();
        watcher->deleteLater();
    });
}

QDBusMessage DaemonDbusInterface::callWithArgumentList(
    const QString &method, const QList<QVariant> &args)
{
    return dbusInterface.callWithArgumentList(QDBus::Block, method, args);
}


void DaemonDbusInterface::openPSR()
{
    QDBusInterface iface(daemon_dbus_service, daemon_dbus_path, daemon_dbus_interface, QDBusConnection::systemBus());
    if (!iface.isValid()) 
    {
        PRINT_DBG("DaemonDbusInterface::openPSR()-- iface.is not Valid()\n");
        return;
    }
    QDBusReply<void> reply = iface.call("OpenPSR");

    // 检查调用是否成功
    if (reply.isValid()) {
        PRINT_DBG("DaemonDbusInterface::openPSR() success\n");
    } else {
        PRINT_DBG("DaemonDbusInterface::openPSR() failed\n");
    }
}

void DaemonDbusInterface::closePSR() {
    QDBusInterface iface(daemon_dbus_service, daemon_dbus_path, daemon_dbus_interface, QDBusConnection::systemBus());
    if (!iface.isValid()) 
    {
        PRINT_DBG("DaemonDbusInterface::closePSR()-- iface.is not Valid()\n");
        return;
    }
    QDBusReply<void> reply = iface.call("ClosePSR");

    // 检查调用是否成功
    if (reply.isValid()) {
        PRINT_DBG("DaemonDbusInterface::closePSR() success\n");
    } else {
        PRINT_DBG("DaemonDbusInterface::closePSR() failed\n");
    }
}

void DaemonDbusInterface::setVRRRefreshRate(std::string mode)
{
    QDBusInterface iface(daemon_dbus_service, daemon_dbus_path, daemon_dbus_interface, QDBusConnection::systemBus());
    if (!iface.isValid()) 
    {
        PRINT_DBG("DaemonDbusInterface::setVRRRefreshRate()-- iface.is not Valid()\n");
        return;
    }
    QDBusReply<void> reply = iface.call("SetVRRRefreshRate", QString::fromStdString(mode));

    // 检查调用是否成功
    if (reply.isValid()) {
        PRINT_DBG("DaemonDbusInterface::setVRRRefreshRate() success\n");
    } else {
        PRINT_DBG("DaemonDbusInterface::setVRRRefreshRate() failed\n");
    }
}

void DaemonDbusInterface::reverseVRRRefreshRate()
{
    QDBusInterface iface(daemon_dbus_service, daemon_dbus_path, daemon_dbus_interface, QDBusConnection::systemBus());
    if (!iface.isValid()) 
    {
        PRINT_DBG("DaemonDbusInterface::reverseVRRRefreshRate()-- iface.is not Valid()\n");
        return;
    }
    QDBusReply<void> reply = iface.call("ReverseVRRRefreshRate");

    // 检查调用是否成功
    if (reply.isValid()) {
        PRINT_DBG("DaemonDbusInterface::reverseVRRRefreshRate() success\n");
    } else {
        PRINT_DBG("DaemonDbusInterface::reverseVRRRefreshRate() failed\n");
    }
}

void DaemonDbusInterface::setSystemdUnitRun(
    const std::string &unitName, bool start)
{
    qDebug() << "DaemonDbusInterface::setSystemdUnitRun: "
             << QString::fromStdString(unitName)
             << start;
    QList<QVariant> argumentList;
    argumentList
        << QVariant::fromValue(QString::fromStdString(unitName))
        << QVariant::fromValue(start);
    asyncCallWithArgumentList("SetSystemdUnitRun", argumentList);
}

void DaemonDbusInterface::setCurrentScene(const std::vector<std::string> &currScenes)
{
    qDebug() << "DaemonDbusInterface::setCurrentScene: "
    << misc::stl2qt::vectorString2QStringList(currScenes);

    QList<QVariant> argumentList;
    argumentList
        << misc::stl2qt::vectorString2QStringList(currScenes);
    asyncCallWithArgumentList("SetCurrentScene", argumentList);
}

void DaemonDbusInterface::setSystemCpuFreq(bool cpufreq)
{
    QDBusInterface iface(daemon_dbus_service, daemon_dbus_path, daemon_dbus_interface, QDBusConnection::systemBus());
    if (!iface.isValid()) 
    {
        PRINT_DBG("-----------------------  1 i am in DaemonDbusInterface::setSystemCpuFreq ,setSystemCpuFreq\n");
        return;
    }
    QDBusReply<void> reply = iface.call("SetSystemCpuFreq", cpufreq);

    // 检查调用是否成功
    if (reply.isValid()) {
        PRINT_DBG("-----------------------  2  i am in DaemonDbusInterface::setSystemCpuFreq ,setSystemCpuFreq\n");
    } else {
        PRINT_DBG("----------------------- 3 i am in DaemonDbusInterface::setSystemCpuFreq ,setSystemCpuFreq\n");
    }
}
void DaemonDbusInterface::SetKernelSched(bool kernelsched)
{
    QDBusInterface iface(daemon_dbus_service, daemon_dbus_path, daemon_dbus_interface, QDBusConnection::systemBus());
    if (!iface.isValid()) 
    {
        PRINT_DBG("-----------------------  1 i am in DaemonDbusInterface::SetKernelSched ,SetKernelSched\n");
        return;
    }
    QDBusReply<void> reply = iface.call("SetKernelSched", kernelsched);

    // 检查调用是否成功
    if (reply.isValid()) {
        PRINT_DBG("-----------------------  2  i am in DaemonDbusInterface::SetKernelSched ,SetKernelSched\n");
    } else {
        PRINT_DBG("----------------------- 3 i am in DaemonDbusInterface::SetKernelSched ,SetKernelSched\n");
    }
}
void DaemonDbusInterface::SetDirty(bool dirty)
{
    QDBusInterface iface(daemon_dbus_service, daemon_dbus_path, daemon_dbus_interface, QDBusConnection::systemBus());
    if (!iface.isValid()) 
    {
        PRINT_DBG("-----------------------  1 i am in DaemonDbusInterface::SetDirty ,SetDirty\n");
        return;
    }
    QDBusReply<void> reply = iface.call("SetDirty", dirty);

    // 检查调用是否成功
    if (reply.isValid()) {
        PRINT_DBG("-----------------------  2  i am in DaemonDbusInterface::SetDirty ,SetDirty\n");
    } else {
        PRINT_DBG("----------------------- 3 i am in DaemonDbusInterface::SetDirty ,SetDirty\n");
    }
}
void DaemonDbusInterface::SetNetParams(bool netparams)
{
    QDBusInterface iface(daemon_dbus_service, daemon_dbus_path, daemon_dbus_interface, QDBusConnection::systemBus());
    if (!iface.isValid()) 
    {
        PRINT_DBG("-----------------------  1 i am in DaemonDbusInterface::SetNetParams ,SetNetParams\n");
        return;
    }
    QDBusReply<void> reply = iface.call("SetNetParams", netparams);

    // 检查调用是否成功
    if (reply.isValid()) {
        PRINT_DBG("-----------------------  2  i am in DaemonDbusInterface::SetNetParams ,SetNetParams\n");
    } else {
        PRINT_DBG("----------------------- 3 i am in DaemonDbusInterface::SetNetParams ,SetNetParams\n");
    }
}
void DaemonDbusInterface::SetCpuLimit(bool cpulimit)
{
    QDBusInterface iface(daemon_dbus_service, daemon_dbus_path, daemon_dbus_interface, QDBusConnection::systemBus());
    if (!iface.isValid()) 
    {
        PRINT_DBG("-----------------------  1 i am in DaemonDbusInterface::SetCpuLimit ,SetCpuLimit\n");
        return;
    }
    QDBusReply<void> reply = iface.call("SetCpuLimit", cpulimit);

    // 检查调用是否成功
    if (reply.isValid()) {
        PRINT_DBG("-----------------------  2  i am in DaemonDbusInterface::SetCpuLimit ,SetCpuLimit\n");
    } else {
        PRINT_DBG("----------------------- 3 i am in DaemonDbusInterface::SetCpuLimit ,SetCpuLimit\n");
    }
}
void DaemonDbusInterface::SetSamplingRate(bool samplingrate)
{
    QDBusInterface iface(daemon_dbus_service, daemon_dbus_path, daemon_dbus_interface, QDBusConnection::systemBus());
    if (!iface.isValid()) 
    {
        PRINT_DBG("-----------------------  1 i am in DaemonDbusInterface::SetSamplingRate ,SetSamplingRate\n");
        return;
    }
    QDBusReply<void> reply = iface.call("SetSamplingRate", samplingrate);

    // 检查调用是否成功
    if (reply.isValid()) {
        PRINT_DBG("-----------------------  2  i am in DaemonDbusInterface::SetSamplingRate ,SetSamplingRate\n");
    } else {
        PRINT_DBG("----------------------- 3 i am in DaemonDbusInterface::SetSamplingRate ,SetSamplingRate\n");
    }
}

