/*
 * Copyright (C) Copyright 2021 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, 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 "sessionhelper.h"
#include <sys/file.h>
#include <pwd.h>
#include <QString>
#include <QDebug>
#include <QDBusMetaType>
#include <QDBusReply>
#include <QDBusInterface>

const static QString sessionService = QStringLiteral("org.gnome.SessionManager");
const static QString sessionPath = QStringLiteral("/org/gnome/SessionManager");
const static QString sessionInterface = QStringLiteral("org.gnome.SessionManager");

QDBusArgument &InhibitInfo::operator<<(QDBusArgument &argument, const InhibitInfo::InhibitorInfo &mystruct)
{
    argument.beginStructure();
    argument << mystruct.name << mystruct.icon;
    argument.endStructure();
    return argument;
}

const QDBusArgument &InhibitInfo::operator>>(const QDBusArgument &argument, InhibitInfo::InhibitorInfo &mystruct)
{
    argument.beginStructure();
    argument >> mystruct.name >> mystruct.icon ;
    argument.endStructure();
    return argument;
}

SessionHelper::SessionHelper(QObject *parent) : QObject(parent)
{
    m_sessionInterface = new QDBusInterface(sessionService,
                                            sessionPath,
                                            sessionInterface,
                                            QDBusConnection::sessionBus(),
                                            this);
}

SessionHelper::~SessionHelper()
{

}

QStringList SessionHelper::getLockCheckStatus(QString type)
{
    qDBusRegisterMetaType<InhibitInfo::InhibitorInfo>();

    QVector<InhibitInfo::InhibitorInfo> resVec;

    if (m_sessionInterface->isValid()) {
        qDebug() << "create interface success";
    }

    QDBusMessage result = m_sessionInterface->call("ListInhibitor", QVariant(type));
    QList<QVariant> outArgs = result.arguments();
    QVariant first = outArgs.at(0);
    const QDBusArgument &dbusArgs = first.value<QDBusArgument>();

    dbusArgs.beginArray();
    while (!dbusArgs.atEnd()) {
        InhibitInfo::InhibitorInfo inhibtor;
        dbusArgs >> inhibtor;
        resVec.push_back(inhibtor);
    }
    dbusArgs.endArray();
    QStringList lockCheckList;
    for (auto iter = resVec.begin(); iter != resVec.end(); ++iter) {
        lockCheckList.append(iter->icon);
        lockCheckList.append(iter->name);
    }
    qDebug() << "lockCheckList = " << lockCheckList;

    return lockCheckList;
}
