/*
 * Copyright (C) 2018 Tianjin KYLIN Information Technology 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, 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 <http://www.gnu.org/licenses/>.
 *
**/
#include <QCoreApplication>
#include <QDBusConnection>
#include <QDebug>
#include <QGSettings>

#include "interface.h"
#include "screensaveradaptor.h"
#include "types.h"

#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
#include <ukui-log4qt.h>

void sig_chld(int /*signo*/)
{
    pid_t pid;
    while( (pid = waitpid(-1, NULL, WNOHANG)) > 0)
        qDebug() << "child" << pid << "terminated";
    return;
}

int main(int argc, char *argv[])
{
    initUkuiLog4qt("ukui-screensaver-backend");
    // 重启或关机时不被session关掉
    qunsetenv("SESSION_MANAGER");
    QCoreApplication a(argc, argv);

    // 检查该程序是否已经有实例在运行
    QDBusInterface *checkInterface =
            new QDBusInterface("org.freedesktop.DBus",
                               "/org/freedesktop/DBus",
                               "org.freedesktop.DBus",
                               QDBusConnection::sessionBus());
    QDBusReply<bool> ret = checkInterface->call("NameHasOwner",
                                               "cn.kylinos.ScreenSaver");
    if(ret.value()) {
        qDebug() << "There is an instance running";
        exit(EXIT_FAILURE);
    }

    // 注册DBus
    Interface *interface = new Interface();
    ScreenSaverAdaptor adaptor(interface);

    QDBusConnection service = QDBusConnection::sessionBus();
    QString sessionDbus = SS_DBUS_SERVICE;
    if(!service.registerService(sessionDbus)) {
        QString displayNum = QString(qgetenv("DISPLAY")).replace(":", "").replace(".", "_");;
        sessionDbus = QString("%1%2").arg(QString(SS_DBUS_SERVICE)).arg(displayNum);
        if(!service.registerService(sessionDbus)) {
            qDebug() << service.lastError().message();
            exit(EXIT_FAILURE);
        }
    }
    if(!service.registerObject(SS_DBUS_PATH, SS_DBUS_SERVICE, &adaptor,
                               QDBusConnection::ExportAllSlots |
                               QDBusConnection::ExportAllSignals)) {
        qDebug() << service.lastError().message();
        exit(EXIT_FAILURE);
    }
    qDebug() << service.baseService();

    QObject::connect(checkInterface, SIGNAL(NameLost(QString)),
                     interface, SLOT(onNameLost(QString)));

    return a.exec();
}
