/*
 * 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 <http://www.gnu.org/licenses/>.
 */
#include <QDesktopWidget>
#include <QApplication>
#include <QDebug>

#include "criticalpercentageaction.h"

#define POWER_MANAGER_SETTINGS            "org.ukui.power-manager"
#define POWER_PERCENTAGE_ACTION           "percentageAction"
#define POWER_ACTION_CRITICAL_BATTERY     "actionCriticalBattery"

CriticalPercentageAction::CriticalPercentageAction(QObject *parent) : QObject(parent)
{
    m_acOnlineState = UpmUpowerDBus::self()->getAcOnlineState();
    connect(UpmUpowerDBus::self(), &UpmUpowerDBus::acOnlineStateChanged,
            this, &CriticalPercentageAction::dealAcOnlineStateChanged);
    connect(UpmUpowerDBus::self(), &UpmUpowerDBus::batteryInfoChanged,
            this, &CriticalPercentageAction::dealBatteryInfoChanged);

    QVariant value;
    if (true == UpmGsettings::self()->getGsettingsConfig(
                GSETTINGS_KEY_PERCENTAGE_ACTION, value)) {
        m_criticalPercentage = value.toInt();
    }
    if (true == UpmGsettings::self()->getGsettingsConfig(
                GSETTINGS_KEY_ACTION_CRITICAL_BATTERY, value)) {
        m_action = value.toString();
    }

    connect(UpmGsettings::self(), &UpmGsettings::percentageActionChanged,
            this, [=](QVariant value) {
        m_criticalPercentage = value.toInt();
    });
    connect(UpmGsettings::self(), &UpmGsettings::actionCriticalBatteryChanged,
            this, [=](QVariant value) {
        m_action = value.toString();
    });

    m_criticalState = false;

    m_timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, this, [=]() {
        doAction();
        stopAction();
    });
}

CriticalPercentageAction::~CriticalPercentageAction()
{
    if (nullptr != m_notificationDialog) {
        delete m_notificationDialog;
        m_notificationDialog = nullptr;
    }
}

void CriticalPercentageAction::dealAcOnlineStateChanged(int index, bool value)
{
    Q_UNUSED(index)
    Q_UNUSED(value)
    qDebug() << "Critical percentage action deal ac online changed";
    m_acOnlineState = value;
    if (true == m_acOnlineState) {
        stopAction();
    } else {
        dealAction();
    }
}

void CriticalPercentageAction::dealBatteryInfoChanged(int index, QStringList batteryInfoChangedList)
{
    Q_UNUSED(index)
    Q_UNUSED(batteryInfoChangedList)
    qDebug() << "Critical percentage action deal battery info changed";
    if (true == m_acOnlineState) {
        stopAction();
    } else {
        dealAction();
    }
}

void CriticalPercentageAction::dealAction()
{
    m_batteryPercentage = UpmUpowerDBus::self()->getBatteryPercentage();
    if (m_batteryPercentage > m_criticalPercentage) {
        return ;
    }

    if ("nothing" == m_action || true == m_criticalState) {
        return ;
    }

    m_fullScreenMask = new FullScreenMask();
    m_fullScreenMask->show();
    kdk::WindowManager::setSkipTaskBar(m_fullScreenMask->windowHandle(), true);
    kdk::WindowManager::setSkipSwitcher(m_fullScreenMask->windowHandle(), true);
    m_notificationDialog = new NotificationDialog();
    connect(m_notificationDialog, &NotificationDialog::dialogClosed,
            m_fullScreenMask, &FullScreenMask::hide);
    m_notificationDialog->setShowMsg(m_action);
    m_notificationDialog->show();
    kdk::WindowManager::setSkipTaskBar(m_notificationDialog->windowHandle(), true);
    kdk::WindowManager::setSkipSwitcher(m_notificationDialog->windowHandle(), true);
    m_notificationDialog->move(
        (QApplication::desktop()->width() - m_notificationDialog->width()) / 2,
        (QApplication::desktop()->height() - m_notificationDialog->height()) / 2);
    m_notificationDialog->start();
    m_criticalState = true;
    m_timer->start(60000);
}

void CriticalPercentageAction::stopAction()
{
    if (m_timer->isActive()) {
        m_timer->stop();

        m_notificationDialog->hide();
        delete m_notificationDialog;
        m_notificationDialog = nullptr;

        m_fullScreenMask->hide();
        delete m_fullScreenMask;
        m_fullScreenMask = nullptr;

        m_criticalState = false;
        qDebug() << "stop critical percentage action timer success";
    }
}

void CriticalPercentageAction::doAction()
{
    QDBusInterface dbusInterface("org.freedesktop.login1",
                                 "/org/freedesktop/login1",
                                 "org.freedesktop.login1.Manager",
                                 QDBusConnection::systemBus());

    qDebug() << "action:" << m_action;
    if ("shutdown" == m_action) {
        dbusInterface.call("PowerOff", true);
    } else if ("hibernate" == m_action) {
        dbusInterface.call("Hibernate", true);
    } else if ("suspend" == m_action){
        dbusInterface.call("Suspend", true);
    } else {
        ;
    }
}
