/*
 * 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 "sessionwatcher.h"
#include <QDBusInterface>
#include <QDebug>
#include <QFile>
#include "types.h"

#define GSETTINGS_SCHEMA_SCREENSAVER "org.ukui.screensaver"
#define KEY_IDLE_DELAY "idleDelay"
#define KEY_IDLE_LOCK "idleLock"
#define KEY_IDLE_ACTIVATION_ENABLED "idleActivationEnabled"
#define KEY_IDLE_LOCK_ENABLED "idleLockEnabled"
#define TIME_TYPE_SCHEMA 			"org.ukui.control-center.panel.plugins"

SessionWatcher::SessionWatcher(QObject *parent) : QObject(parent)
{
    sessionPath = qgetenv("XDG_SESSION_PATH");

    QDBusInterface *interface = new QDBusInterface(
                SM_DBUS_SERVICE,
                SM_DBUS_PATH,
                SM_DBUS_INTERFACE,
                QDBusConnection::sessionBus());

    connect(interface, SIGNAL(StatusChanged(unsigned int)),
            this, SLOT(onStatusChanged(unsigned int)));

    QDBusInterface *displayManagerInterface = new QDBusInterface(
                DM_DBUS_SERVICE,
                DM_DBUS_PATH,
                DM_DBUS_INTERFACE,
                QDBusConnection::systemBus());
    connect(displayManagerInterface, SIGNAL(SessionRemoved(QDBusObjectPath)),
            this, SLOT(onSessionRemoved(QDBusObjectPath)));

    settings_delay = new QGSettings(GSETTINGS_SCHEMA_SCREENSAVER, "", this);
    connect(settings_delay, &QGSettings::changed,
            this, &SessionWatcher::onConfigurationDelayChanged);
    idleDelay = settings_delay->get("idle-delay").toInt();

    settings_lock = new QGSettings(GSETTINGS_SCHEMA_SCREENSAVER, "", this);
    connect(settings_lock, &QGSettings::changed,
            this, &SessionWatcher::onConfigurationLockChanged);
    idleLock = settings_lock->get("idle-lock").toInt();

    QString userName = getenv("USER");
    QString configPath;
    configPath = QString("/var/lib/lightdm-data/%1/ukui-greeter.conf").arg(userName);
    QFile fileConf(configPath);
    if (!fileConf.exists()) {
        QFile file(configPath);
        file.setPermissions(QFile::WriteUser | QFile::ReadUser | QFile::WriteOther | QFile::ReadOther);
    }
    configSettings = new QSettings(configPath, QSettings::IniFormat, this);
    if(QGSettings::isSchemaInstalled(TIME_TYPE_SCHEMA))
        timegsettings = new QGSettings(TIME_TYPE_SCHEMA,"",this);
    int timeType = timegsettings->get("hoursystem").toInt();
    setValue("timeType",timeType);
    QString dateType = timegsettings->get("date").toString();
    setValue("dateType",dateType);
    connect(timegsettings, &QGSettings::changed,
            this, &SessionWatcher::onConfigurationTimeTpChanged);

//    activationEnabled_Key = new QGSettings(GSETTINGS_SCHEMA_SCREENSAVER, "", this);
//    connect(activationEnabled_Key, &QGSettings::changed,
//            this, &SessionWatcher::activationEnabledChanged);
//    idleActivationEnabled = activationEnabled_Key->get("idle-activation-enabled").toBool();

//    lockEnabled_Key = new QGSettings(GSETTINGS_SCHEMA_SCREENSAVER, "", this);
//    connect(lockEnabled_Key, &QGSettings::changed,
//            this, &SessionWatcher::lockEnabledChanged);
//    lockEnabled = lockEnabled_Key->get("idle-lock-enabled").toBool();
//    qDebug()<<lockEnabled;
}
 
void SessionWatcher::onConfigurationDelayChanged(QString key)
{
    if(key == KEY_IDLE_DELAY){
        idleDelay = settings_delay->get("idle-delay").toInt();
    }
}

void SessionWatcher::onConfigurationLockChanged(QString key)
{
    if(key == KEY_IDLE_LOCK){
        idleLock = settings_lock->get("idle-lock").toInt();
    }
}

void SessionWatcher::onConfigurationTimeTpChanged(QString key)
{
    if(key == "hoursystem"){
        int timeType = timegsettings->get("hoursystem").toInt();
        setValue("timeType",timeType);
    }
    if(key == "date"){
        qDebug()<<"jinlaile~~~~~~~~~~~~~~key="<<key;
        QString dateType = timegsettings->get("date").toString();
        qDebug()<<"lsadjfldsa"<<dateType;
        setValue("dateType",dateType);
    }
}

void SessionWatcher::setValue(const QString &key, const QVariant &value)
{
    configSettings->beginGroup("Greeter");
    configSettings->setValue(key, value);
    configSettings->endGroup();
}

//void SessionWatcher::activationEnabledChanged(QString key)
//{
//    if(key == KEY_IDLE_ACTIVATION_ENABLED){
//        idleActivationEnabled = activationEnabled_Key->get("idle-activation-enabled").toBool();
//    }
//}

//void SessionWatcher::lockEnabledChanged(QString key)
//{
//    if(key == KEY_IDLE_LOCK_ENABLED){
//        lockEnabled = lockEnabled_Key->get("idle-lock-enabled").toBool();
//    }
//}

void SessionWatcher::onStatusChanged(unsigned int status)
{
    if(status == SESSION_IDLE) {
        if(idleDelay != -1){
            if(!m_timer){
                m_timer = new QTimer(this);
                connect(m_timer, &QTimer::timeout, this, [&]{
                    Q_EMIT sessionIdle();
                    m_timer->stop();
                });
            }
            int time = (idleDelay - 1)*60000;
            if(time<0)
                time = 0;

            m_timer->start(time);
         }

        if(idleLock != -1){
            if(!m_timer2){
                m_timer2 = new QTimer(this);
                connect(m_timer2, &QTimer::timeout, this, [&]{
                    Q_EMIT sessionLockIdle();
                    m_timer2->stop();
                });
            }
            int lockTime = (idleLock - 1)*60000;
            if(lockTime<0)
                lockTime = 0;

            m_timer2->start(lockTime);
        }


    }else if(status == SESSION_AVAILABLE){
        if(m_timer && m_timer->isActive()){
            m_timer->stop();
        }
        if(m_timer2 && m_timer2->isActive()){
            m_timer2->stop();
        }
    }
}

void SessionWatcher::onSessionRemoved(const QDBusObjectPath &objectPath)
{
    //如果session注销了，则结束进程
    if(objectPath.path() == sessionPath)
        exit(0);
}
