/*
 * Copyright (C) 2019 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  Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1, 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/&gt;.
 *
 */

#include "startmenu_button.h"

#define ORG_UKUI_STYLE            "org.ukui.style"
#define STYLE_NAME                "styleName"

StartMenuButton::StartMenuButton(IUKUIPanelPlugin *plugin, QWidget* parent ):
    QToolButton(parent),
    m_parent(parent),
    m_plugin(plugin)
{
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    setProperty("useButtonPalette",true);
    setAutoRaise(true);
    setSystemStyle();
    const QByteArray id(ORG_UKUI_STYLE);
    if (QGSettings::isSchemaInstalled(id)) {
        m_gsettings = new QGSettings(id);
        connect(m_gsettings, &QGSettings::changed, this, [=] (const QString &key) {
            if (key==STYLE_NAME) {
                setSystemStyle();
            }
        });
    }
    this->setIcon(QIcon::fromTheme("kylin-startmenu",QIcon("/usr/share/ukui-panel/panel/img/startmenu.svg")));
    QTimer::singleShot(5000,[this] {this->setToolTip(tr("UKUI Menu")); });
    this->setIconSize(QSize(m_plugin->panel()->iconSize(),m_plugin->panel()->iconSize()));
}

StartMenuButton::~StartMenuButton()
{
}

void StartMenuButton::setSystemStyle()
{
    QPalette pal = this->palette();
    QColor col = pal.color(QPalette::Active, QPalette::BrightText);
    col.setAlphaF(0.13);
    pal.setColor(QPalette::Button, col);
    this->setPalette(pal);
}

/*plugin-startmenu refresh function*/
void StartMenuButton::realign()
{
    if (m_plugin->panel()->isHorizontal())
        this->setFixedSize(m_plugin->panel()->panelSize(),m_plugin->panel()->panelSize());
    else
        this->setFixedSize(m_plugin->panel()->panelSize(),m_plugin->panel()->panelSize());
    this->setIconSize(QSize(m_plugin->panel()->iconSize(),m_plugin->panel()->iconSize()));
}

void StartMenuButton::mouseReleaseEvent(QMouseEvent* event)
{
    const Qt::MouseButton b = event->button();

    if (Qt::LeftButton == b)
    {
        QDBusInterface iface("org.ukui.menu",
                             "/org/ukui/menu",
                             "org.ukui.menu",
                             QDBusConnection::sessionBus());
        iface.asyncCall("WinKeyResponse");
    }
    QToolButton::mouseReleaseEvent(event);
}

void StartMenuButton::contextMenuEvent(QContextMenuEvent *event)
{
    rightPressMenu = new QMenu(this);
    rightPressMenu->setAttribute(Qt::WA_DeleteOnClose);

    QMenu *pUserAction = new QMenu(tr("User Action"), this);              //用户操作
    QMenu *pSleepHibernate = new QMenu(tr("Suspend or Hibernate"), this);   //休眠或睡眠
    QMenu *pPowerSupply = new QMenu(tr("Power Supply"), this);            //电源
    rightPressMenu->addMenu(pUserAction);
    if (QString::compare(getCanHibernateResult(),"yes") == 0 ||
        QString::compare(getCanSuspendResult(),"yes") == 0) {
        rightPressMenu->addMenu(pSleepHibernate);
    }
    rightPressMenu->addMenu(pPowerSupply);

    pUserAction->addAction(QIcon::fromTheme("system-lock-screen-symbolic"),
                           tr("Lock Screen"),
                           this, SLOT(ScreenServer())
                           );                                     //锁屏
    if (hasMultipleUsers() && canSwitch()) {
        pUserAction->addAction(QIcon::fromTheme("stock-people-symbolic"),
                               tr("Switch User"),
                               this, SLOT(SessionSwitch())
                               );                                     //切换用户
    }
    pUserAction->addAction(QIcon::fromTheme("system-log-out-symbolic"),
                           tr("Log Out"),
                           this, SLOT(SessionLogout())
                           );                                     //注销

    if(QString::compare(getCanHibernateResult(),"yes") == 0){
        pSleepHibernate->addAction(QIcon::fromTheme("kylin-sleep-symbolic"),
                                   tr("Hibernate"),
                                   this, SLOT(SessionHibernate())
                                   );                              //休眠
    }
    if(QString::compare(getCanSuspendResult(),"yes") == 0)
    {
        pSleepHibernate->addAction(QIcon::fromTheme("ukui-hebernate-symbolic"),
                                   tr("Suspend"),
                                   this, SLOT(SessionSuspend())
                                   );                                   //睡眠
    }
    pPowerSupply->addAction(QIcon::fromTheme("system-reboot-symbolic"),
                            tr("Restart"),
                            this, SLOT(SessionReboot())
                            );                                      //重启
    QFileInfo file("/usr/bin/time-shutdown");
    if(file.exists())
        pPowerSupply->addAction(QIcon::fromTheme("ukui-shutdown-timer-symbolic"),
                                tr("TimeShutdown"),
                                this, SLOT(TimeShutdown())
                                );                                  //定时开关机
    pPowerSupply->addAction(QIcon::fromTheme("system-shutdown-symbolic"),
                            tr("Shut Down"),
                            this, SLOT(SessionShutdown())
                            );                                      //关机

    rightPressMenu->setGeometry(m_plugin->panel()->calculatePopupWindowPos(mapToGlobal(event->pos()), rightPressMenu->sizeHint()));
    rightPressMenu->show();
    //解决触摸长按时显示出右键菜单后，按钮三态不消失问题
    QObject::connect(rightPressMenu, &QMenu::destroyed, this, [&](){
        this->setAttribute(Qt::WA_UnderMouse, false);
        this->setDown(false);
        this->update();
    });
}

/*开始菜单按钮右键菜单选项，与开始菜单中电源按钮的右键功能是相同的*/
//锁屏
void StartMenuButton::ScreenServer()
{
    system("ukui-screensaver-command -l");
}

//切换用户
void StartMenuButton::SessionSwitch()
{
    QProcess::startDetached(QString("ukui-session-tools --switchuser"));
}

//注销
void StartMenuButton::SessionLogout()
{
    system("ukui-session-tools --logout");
}

//休眠 睡眠
void StartMenuButton::SessionHibernate()
{
    system("ukui-session-tools --hibernate");
}

//睡眠
void StartMenuButton::SessionSuspend()
{
    system("ukui-session-tools --suspend");
}

//重启
void StartMenuButton::SessionReboot()
{
    system("ukui-session-tools --reboot");
}

//定时关机
void StartMenuButton::TimeShutdown()
{
    QProcess *process_timeshutdowm =new QProcess(this);
    process_timeshutdowm->startDetached("/usr/bin/time-shutdown");
    process_timeshutdowm->deleteLater();
}

//关机
void StartMenuButton::SessionShutdown()
{
    system("ukui-session-tools --shutdown");
}

//获取系统版本,若为ubuntu则取消休眠功能
void StartMenuButton::getOsRelease()
{
    QFile file("/etc/lsb-release");
    if (!file.open(QIODevice::ReadOnly)) qDebug() << "Read file Failed.";
    while (!file.atEnd()) {
        QByteArray line = file.readLine();
        QString str(line);
        if (str.contains("DISTRIB_ID")){
            version=str.remove("DISTRIB_ID=");
            version=str.remove("\n");
        }
    }
}

//检测当前系统能否执行休眠操作
QString StartMenuButton::getCanHibernateResult()
{
    QDBusInterface interface(LOGIN_SERVICE, LOGIN_PATH,
                             LOGIN_INTERFACE, QDBusConnection::systemBus());
    if (!interface.isValid()) {
        qCritical() << QDBusConnection::sessionBus().lastError().message();
        return QString("");
    }
    /*调用远程的 CanHibernate 方法，判断是否可以执行休眠的操作,返回值为yes为允许执行休眠，no为无法执行休眠 na为交换分区不足*/
    QDBusReply<QString> reply = interface.call("CanHibernate");
    if (reply.isValid()) {
        return reply.value();
    } else {
        qCritical() << "Call Dbus method failed";
        return QString("");
    }
}

//检测当前系统能否执行睡眠操作
QString StartMenuButton::getCanSuspendResult()
{
    QDBusInterface interface(LOGIN_SERVICE, LOGIN_PATH,
                             LOGIN_INTERFACE, QDBusConnection::systemBus());
    if (!interface.isValid()) {
        qCritical() << QDBusConnection::sessionBus().lastError().message();
        return QString("");
    }
    QDBusReply<QString> reply = interface.call("CanSuspend");
    if (reply.isValid()) {
        return reply.value();
    } else {
        qCritical() << "Call Dbus method failed";
        return QString("");
    }
}

bool StartMenuButton::hasMultipleUsers()
{
    QDBusInterface interface("org.freedesktop.Accounts",
                             "/org/freedesktop/Accounts",
                             "org.freedesktop.DBus.Properties",
                             QDBusConnection::systemBus());
    if (!interface.isValid()) {
        qCritical() << QDBusConnection::systemBus().lastError().message();
        return false;
    }

    QDBusReply<QVariant> reply = interface.call("Get","org.freedesktop.Accounts","HasMultipleUsers");
    return reply.value().toBool();
}

bool StartMenuButton::canSwitch()
{
    QDBusInterface interface("org.freedesktop.DisplayManager",
                             "/org/freedesktop/DisplayManager/Seat0",
                             "org.freedesktop.DBus.Properties",
                             QDBusConnection::systemBus());
    if (!interface.isValid()) {
        qCritical() << QDBusConnection::systemBus().lastError().message();
        return false;
    } else {
        QDBusReply<QVariant> reply = interface.call("Get","org.freedesktop.DisplayManager.Seat","CanSwitch");
	return reply.value().toBool();
    }
}
void StartMenuButton::enterEvent(QEvent *) {
    repaint();
    return;
}

void StartMenuButton::leaveEvent(QEvent *) {
    repaint();
    return;
}
