/*
 * Copyright (C) 2025, 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/>.
 *
 * Authors: liuliang <liuliang@kylinos.cn>
 *
 */

#include "systemserviceregister.h"

#include <QDBusConnection>
#include <QDBusInterface>

#include <QProcess>
#include <QDebug>

SystemServiceRegister::SystemServiceRegister(QObject *parent)
    : ServiceRegister{parent}
{

}

bool SystemServiceRegister::registerServicesInternal(const QString &pluginPath, const QStringList &serviceNames, const QString &serviceSpace, bool resident, const QStringList &args)
{
    bool successed = false;

    // 判断是否存在对应serviceSpace服务，如果不存在则拉起serviceSpace的进程
    QString serviceName = QString("org.ukui.Service.%1").arg(serviceSpace);
    qDebug() << serviceName << serviceSpace << resident;
    QString servicePath = "/org/ukui/ServiceSpace/" + serviceSpace;
    QString serviceInterface = "org.ukui.ServiceSpace." + serviceSpace;
    QDBusInterface interface(serviceName, servicePath, serviceInterface, QDBusConnection::systemBus(), nullptr);
    if (interface.isValid()) {
        auto message = interface.call(QDBus::Block, "launchServices", pluginPath, serviceNames, resident);
        auto args = message.arguments();
        if (!args.isEmpty()) {
            return args.first().toBool();
        } else {
            qCritical() << message.errorMessage();
            return false;
        }
    } else {
        QStringList tmpServices;
        for (auto tmpString : serviceNames) {
            tmpServices << "-s" << tmpString;
        }
        QProcess p;
        p.setProgram("ukui-system-service");
        QStringList tmp = QStringList() << "-p" << pluginPath << "-n" << serviceSpace << "-r" << (resident? "true": "false") << tmpServices;
        for (auto arg : args) {
            tmp << "-a" << arg;
        }
        p.setArguments(tmp);
        p.startDetached();
        while(1) {
            QDBusInterface interface(serviceName, "/", QString(), QDBusConnection::systemBus(), nullptr);
            if (interface.isValid()) {
                return true;
            }
        }
    }

    return successed;
}
