#include "maintainmode.h"

#include <QApplication>
#include <QColor>
#include <QDir>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QSettings>
#include <QTranslator>
#include <QVBoxLayout>
#include <QtDBus/QDBusMessage>
#include <QtDBus/QDBusPendingCall>
#include <QtDBus/QDBusReply>
#include <QtDebug>
#include <polkit-qt5-1/polkitqt1-authority.h>

const QString MAINTAINMODECONF = "/ostree/pkgs/ostree-ovl.conf";
const QString MMDBUSSERVICE = "com.kylin.MaintainMode";
const QString MMDBUSPATH = "/com/kylin/MaintainMode/Object";
const QString MMDBUSINTERFACE = "com.kylin.MaintainMode.interface";

const QString WMBUSSERVICE = "com.kylin.MaintainMode.watermark";
const QString WMDBUSPATH = "/com/kylin/MaintainMode/watermark";
const QString WMDBUSINTERFACE = "com.kylin.MaintainMode.watermark";
const QString WMDBUSSIGNALOFWM = "waterMaskChanged";

#define MAX_SYNC_TIME 300000

MaintainMode::MaintainMode()
{
    QTranslator *translator = new QTranslator(this);
    translator->load("/usr/share/maintainmode/translations/" + QLocale::system().name());
    QApplication::installTranslator(translator);
    pluginName = tr("Maintain Mode");
    pluginType = SYSTEM;
    iface = new QDBusInterface(MMDBUSSERVICE,
                               MMDBUSPATH,
                               MMDBUSINTERFACE,
                               QDBusConnection::systemBus(),
                               this);
    wmIface = new QDBusInterface(
        WMBUSSERVICE,
        WMDBUSPATH,
        WMDBUSINTERFACE,
        QDBusConnection::sessionBus(),
        this);
    connect(this, &MaintainMode::inHibitChanged, this, &MaintainMode::mInhibitStatus);
}

MaintainMode::~MaintainMode()
{
}

QString MaintainMode::plugini18nName()
{
    return pluginName;
}

int MaintainMode::pluginTypes()
{
    return pluginType;
}

QWidget *MaintainMode::pluginUi()
{
    if (mFirstLoad == false) {
        return pluginWidget;
    }
    mFirstLoad = false;
    pluginWidget = new QWidget;
    pluginWidget->setAttribute(Qt::WA_DeleteOnClose);
    initUI(pluginWidget);
    connect(mEnableButton, &kdk::KSwitchButton::stateChanged, this, [this](bool status) {
        if (!mEnableButtonStatus && status) {
            if (!enterMaintainWarning()) {
                mEnableButton->setChecked(false);
                return;
            }
        }
        normalExitMaintain();
        if (mEnableButtonStatus == status)
            return;

        bool checkpolkit = polkitEdit();
        if (!checkpolkit) {
            mEnableButton->setChecked(mEnableButtonStatus);
            return;
        }
        if (status) {
            mEnableButtonComfirmSlot(); // #376903 重启生效后，显示额外的下拉框；立即生效要设置下面的状态
        } else {
            mLineUnderEnableFrame->setVisible(status);
            mExpandFrame_1->setVisible(status);
            mLineUnderExpandArea1->setVisible(status);
            mExpandFrame_2->setVisible(status);
            mLineUnderExpandArea2->setVisible(status && mExpandButton_2->isChecked);
            mExpandFrame_3->setVisible(status && mExpandButton_2->isChecked);
            mEnableButtonSlot(status);
            mExpandButton_1->setChecked(status);
        }
    });
    connect(mExpandButton_2, &DrownLabel::labelClicked, this, [this]() {
        if (mExpandButton_2->isChecked) {
            mExpandButton_2->setDropDownStatus(false);
            mExpandFrame_3->hide();
            mLineUnderExpandArea2->hide();
        } else {
            mExpandButton_2->setDropDownStatus(true);
            mExpandFrame_3->show();
            mLineUnderExpandArea2->show();
        }
    });
    connect(radioGreen, &QRadioButton::clicked, [&]() {
        isRedButton = false;
        mSendSignalOfWatermask();
    });
    connect(radioRed, &QRadioButton::clicked, [&]() {
        isRedButton = true;
        mSendSignalOfWatermask();
    });
    connect(mFontBox, &QComboBox::currentTextChanged, this, &MaintainMode::mSendSignalOfWatermask);
    connect(mPosisionBox, &QComboBox::currentTextChanged, this, &MaintainMode::mSendSignalOfWatermask);
    return pluginWidget;
}

bool MaintainMode::polkitEdit()
{
    PolkitQt1::Authority::Result result;
    // PolkitQt1::SystemBusNameSubject subject(message().service());

    result = PolkitQt1::Authority::instance()->checkAuthorizationSync(
        "org.kylin.ostree_maintain.action",
        PolkitQt1::UnixProcessSubject(QCoreApplication::applicationPid()),
        PolkitQt1::Authority::AllowUserInteraction);
    if (result == PolkitQt1::Authority::Yes) { // 认证通过
        qDebug() << QString("operation authorized");
        return true;
    } else {
        qDebug() << QString("not authorized");
        return false;
    }
}

const QString MaintainMode::name() const
{
    return QStringLiteral("MaintainMode");
}

bool MaintainMode::isShowOnHomePage() const
{
    return false;
}

QIcon MaintainMode::icon() const
{
    //    TODO 替换为维护模式的 icon
    return QIcon::fromTheme("ukui-developer-symbolic");
}

bool MaintainMode::isEnable() const
{
    return true;
}

QString MaintainMode::translationPath() const
{
    return QStringLiteral("/usr/share/maintainmode/translations/%1.ts");
}

void MaintainMode::initUI(QWidget *widget)
{
    //    总体垂直布局
    QVBoxLayout *totalVBoxLayout = new QVBoxLayout(widget);
    totalVBoxLayout->setSpacing(8);
    totalVBoxLayout->setContentsMargins(0, 0, 0, 0);

    //    Title Area
    mTitleLabel = new TitleLabel(widget);
    mTitleLabel->setText(tr("Maintain Mode"));
    totalVBoxLayout->addWidget(mTitleLabel);

    //    Master Frame
    mMasterFrame = new QFrame(widget);
    mMasterFrame->setMinimumSize(QSize(550, 0));
    mMasterFrame->setFixedHeight(60);  
    mMasterFrame->setMaximumSize(QSize(16777215, 16777215));
    mMasterFrame->setFrameShape(QFrame::Box);

    QVBoxLayout *masterLyt = new QVBoxLayout(mMasterFrame);
    masterLyt->setContentsMargins(0, 0, 0, 0);
    masterLyt->setSpacing(0);

    //    Eable Area
    mEnableFrame = new QFrame(mMasterFrame);
    setFrameNoFrame(mEnableFrame);

    mEnableLabel = new QLabel(tr("Maintain Mode"), mEnableFrame);
    mEnableLabel->setContentsMargins(0, 12, 0, 0);
    mEnbleSubLabel = new LightLabel(tr("Allows installation of apps from any software repository and debugging of the runtime environment, etc."), mEnableFrame);
    mEnbleSubLabel->setContentsMargins(0, 0, 0, 12);
    mEnableButton = new kdk::KSwitchButton(mEnableFrame);
    QVariant modeValueInConf = readIniFile(MAINTAINMODECONF, "boot", "mode");
    if (!modeValueInConf.isNull()) {
        mEnableButtonStatus = modeValueInConf.toString() == "maintain" ? true : false;
        qDebug() << "[Maintain Mode]The Key <mode>'s Value in conf is: " << modeValueInConf.toString();
    }
    mEnableButton->setChecked(mEnableButtonStatus);

    QVBoxLayout *enableLabelLyt = new QVBoxLayout();
    enableLabelLyt->setContentsMargins(0, 0, 0, 0);
    enableLabelLyt->setSpacing(0);
    QHBoxLayout *enableLyt = new QHBoxLayout(mEnableFrame);
    enableLyt->setContentsMargins(16, 0, 16, 0);
    enableLyt->setSpacing(0);
    enableLyt->addLayout(enableLabelLyt);

    enableLabelLyt->addWidget(mEnableLabel);
    enableLabelLyt->addWidget(mEnbleSubLabel);

    enableLyt->addStretch();
    enableLyt->addWidget(mEnableButton);

    masterLyt->addWidget(mEnableFrame);

    //    Expand Area_1
    mExpandFrame_1 = new QFrame(mMasterFrame);
    setFrameNoFrame(mExpandFrame_1);
    mExpandFrame_1->setVisible(mEnableButtonStatus);

    mLineUnderEnableFrame = setLine(mMasterFrame);
    mLineUnderEnableFrame->setVisible(mEnableButtonStatus);

    mExpandLabel_1 = new QLabel(tr("Allow to save the data of maintain mode"), mExpandFrame_1);
    mExpandLabel_1->setContentsMargins(0, 12, 0, 0);
    mExpandSubLabel_1 = new LightLabel(tr("Changes applied during maintain mode will persist after the feature is disabled"), mExpandFrame_1);
    mExpandSubLabel_1->setContentsMargins(0, 0, 0, 12);
    mExpandButton_1 = new kdk::KSwitchButton(mExpandFrame_1);
    mExpandButton_1->setChecked(true);

    QHBoxLayout *expandLyt_1 = new QHBoxLayout(mExpandFrame_1);
    expandLyt_1->setContentsMargins(16, 0, 16, 0);
    expandLyt_1->setSpacing(0);
    QVBoxLayout *expandSubLyt_1 = new QVBoxLayout();
    expandSubLyt_1->setContentsMargins(0, 0, 0, 0);
    expandSubLyt_1->setSpacing(0);
    expandSubLyt_1->addWidget(mExpandLabel_1);
    expandSubLyt_1->addWidget(mExpandSubLabel_1);
    expandLyt_1->addLayout(expandSubLyt_1);
    expandLyt_1->addStretch();
    expandLyt_1->addWidget(mExpandButton_1);

    masterLyt->addWidget(mLineUnderEnableFrame);
    masterLyt->addWidget(mExpandFrame_1);

    //    Expand Area_2
    mExpandFrame_2 = new QFrame(mMasterFrame);
    setFrameNoFrame(mExpandFrame_2);
    mExpandFrame_2->setVisible(mEnableButtonStatus);

    mLineUnderExpandArea1 = setLine(mMasterFrame);
    mLineUnderExpandArea1->setVisible(mEnableButtonStatus);
    mExpandLabel_2 = new QLabel(tr("the Watermask of Maintain Mode"), mExpandFrame_2);
    mExpandButton_2 = new DrownLabel(mExpandFrame_2);

    QHBoxLayout *expandLyt_2 = new QHBoxLayout(mExpandFrame_2);
    expandLyt_2->setContentsMargins(16, 0, 16, 0);
    expandLyt_2->setSpacing(4);
    expandLyt_2->addWidget(mExpandLabel_2);
    expandLyt_2->addStretch();
    expandLyt_2->addWidget(mExpandButton_2);

    masterLyt->addWidget(mLineUnderExpandArea1);
    masterLyt->addWidget(mExpandFrame_2);

    //    Expand Area_3zz
    mExpandFrame_3 = new QFrame(mMasterFrame);
    mExpandFrame_3->setMinimumSize(QSize(550, 180));
    mExpandFrame_3->setFrameShape(QFrame::NoFrame);
    mExpandFrame_3->setVisible(mExpandButton_2->isChecked && mEnableButtonStatus);

    mLineUnderExpandArea2 = setLine(mMasterFrame);
    mLineUnderExpandArea2->setVisible(mExpandButton_2->isChecked && mEnableButtonStatus);
    mExpandLabel_3_Color = new QLabel(tr("Color"), mExpandFrame_3);

    // 红色按钮（始终保持红色）
    radioRed = new QRadioButton();
    radioRed->setStyleSheet(
        "QRadioButton::indicator {"
        "    width: 30px;"
        "    height: 30px;"
        "    border-radius: 15px;"  // 圆形
        "}"
        "QRadioButton::indicator:unchecked {"
        "    background-color: red;"
        "}"
        "QRadioButton::indicator:checked {"         
			"width: 30px;"
    		"height: 30px;"
    		"background-color: qradialgradient(spread:pad, cx:0.5, cy:0.5, radius:0.5, fx:0.5, fy:0.5, stop:0 red, stop:0.6 red,stop:0.65 rgba(255, 255, 255, 0), stop:0.8 rgba(255, 255, 255, 0), stop:0.85 red, stop:1 red);"
    		"border: 3px red;"
			"border-radius: 15px;"
        "}"
    );

    // 绿色按钮（始终保持绿色）
    radioGreen = new QRadioButton("");
    radioGreen->setStyleSheet(
        "QRadioButton::indicator {"
        "    width: 30px;"
        "    height: 30px;"
        "    border-radius: 15px;"  // 圆形
        "}"
        "QRadioButton::indicator:unchecked {"
        "    background-color: green;"
        "}"
        "QRadioButton::indicator:checked {"         
			"width: 30px;"
    		"height: 30px;"
    		"background-color: qradialgradient(spread:pad, cx:0.5, cy:0.5, radius:0.5, fx:0.5, fy:0.5, stop:0 green, stop:0.6 green,stop:0.65 rgba(255, 255, 255, 0), stop:0.8 rgba(255, 255, 255, 0), stop:0.85 green, stop:1 green);"
    		"border: 3px green;"
			"border-radius: 15px;"
        "}"
    );
    QString configFilePath = QDir::homePath() + "/.config/mm-watermark.conf";
    QString configColor = readIniFile(configFilePath, "watermark", "fontColor").toString();
    if (!QFile::exists(configFilePath) || configColor.compare("red", Qt::CaseInsensitive) == 0) {
        isRedButton = true;
        radioRed->setChecked(true);
    } else {
        isRedButton = false;
        radioGreen->setChecked(true);
    }

    // 创建水平布局并添加按钮
    QHBoxLayout *radioLayout = new QHBoxLayout();
    radioLayout->addStretch();
    radioLayout->addWidget(radioRed);
    radioLayout->addWidget(radioGreen);
    radioLayout->setSpacing(50);  // 按钮间距
    radioLayout->setContentsMargins(2, 0, 2, 0); // 减少布局边距

    QWidget *radioContainer = new QWidget(mExpandFrame_3);  // 创建容器控件
    radioContainer->setLayout(radioLayout);                // 将水平布局设置到容器中
    radioContainer->setMinimumSize(QSize(550, 60));
    radioContainer->setFixedHeight(60);  
    radioContainer->setMaximumSize(QSize(16777215, 60));
    mExpandLabel_3_Font = new QLabel(tr("Font"), mExpandFrame_3);
    mFontBox = new QComboBox(mExpandFrame_3);
    mFontBox->addItems(QStringList() << "20"
                                     << "30");
    QString configFont = readIniFile(configFilePath, "watermark", "fontSize").toString();
    if (!QFile::exists(configFilePath) || configFont.compare("20", Qt::CaseInsensitive) == 0) {
        mFontBox->setCurrentText("20");
    } else {
        mFontBox->setCurrentText("30");
    }
    mExpandLabel_3_Posision = new QLabel(tr("Position"), mExpandFrame_3);
    mPosisionBox = new QComboBox(mExpandFrame_3);
    mPosisionBox->addItems(QStringList() << tr("BottomRight")
                                         << tr("TopLeft")
                                         << tr("TopRight"));
    QString configPos = readIniFile(configFilePath, "watermark", "fontPos").toString();
    if (!QFile::exists(configFilePath) || configPos.compare("BottomRight", Qt::CaseInsensitive) == 0) {
        mPosisionBox->setCurrentText(tr("BottomRight"));
    } else if (configPos.compare("TopLeft", Qt::CaseInsensitive) == 0) {
        mPosisionBox->setCurrentText(tr("TopLeft"));
    } else if (configPos.compare("TopRight", Qt::CaseInsensitive) == 0) {
        mPosisionBox->setCurrentText(tr("TopRight"));
    }
    inline1 = setLine(mMasterFrame);
    inline2 = setLine(mMasterFrame);
 
    QGridLayout *expandLyt_3 = new QGridLayout(mExpandFrame_3);

    QHBoxLayout *row0Layout = new QHBoxLayout; 
    row0Layout->setContentsMargins(16, 0, 16, 0);  
    row0Layout->addWidget(mExpandLabel_3_Color); 
    row0Layout->addStretch();
    row0Layout->addWidget(radioContainer); 
    QWidget *row0Widget = new QWidget; 
    row0Widget->setLayout(row0Layout);
    expandLyt_3->addWidget(row0Widget, 0, 0, 1, 3); // 跨3列

    expandLyt_3->addWidget(inline1, 1, 0, 1, 3); 

    QHBoxLayout *row1Layout = new QHBoxLayout; 
    row1Layout->setContentsMargins(16, 0, 16, 0);  
    row1Layout->addWidget(mExpandLabel_3_Font); 
    row1Layout->addStretch();
    row1Layout->addWidget(mFontBox);
    QWidget *row1Widget = new QWidget; 
    row1Widget->setLayout(row1Layout);
    expandLyt_3->addWidget(row1Widget, 2, 0, 1, 3); // 跨3列

    expandLyt_3->addWidget(inline2, 3, 0, 1, 3); 

    QHBoxLayout *row2Layout = new QHBoxLayout; 
    row2Layout->setContentsMargins(16, 0, 16, 0);  
    row2Layout->addWidget(mExpandLabel_3_Posision); 
    row2Layout->addStretch();
    row2Layout->addWidget(mPosisionBox);
    QWidget *row2Widget = new QWidget; 
    row2Widget->setLayout(row2Layout);
    expandLyt_3->addWidget(row2Widget, 4, 0, 1, 3); // 跨3列

    expandLyt_3->setContentsMargins(0, 0, 0, 0);

    expandLyt_3->setRowMinimumHeight(0, 60);  // 水印颜色所在行（第0行）
    expandLyt_3->setRowMinimumHeight(2, 60);  // 字体大小所在行（第2行）
    expandLyt_3->setRowMinimumHeight(4, 60);  // 显示位置所在行（第4行）

    masterLyt->addWidget(mLineUnderExpandArea2);
    masterLyt->addWidget(mExpandFrame_3);

    //    总
    totalVBoxLayout->addWidget(mMasterFrame);
    totalVBoxLayout->addStretch();
}

inline void MaintainMode::setFrameNoFrame(QFrame *frame)
{
    frame->setMinimumSize(QSize(550, 70));
    frame->setMaximumSize(QSize(16777215, 70));
    frame->setFrameShape(QFrame::NoFrame);
}

inline QFrame *MaintainMode::setLine(QFrame *frame)
{
    QFrame *line = new QFrame(frame);
    line->setMinimumSize(QSize(0, 1));
    line->setMaximumSize(QSize(16777215, 1));
    line->setLineWidth(0);
    line->setFrameShape(QFrame::HLine);
    line->setFrameShadow(QFrame::Sunken);
    return line;
}

bool MaintainMode::enterMaintainWarning()
{
    QMessageBox msgBox(pluginWidget);
    msgBox.setWindowModality(Qt::WindowModal);
    msgBox.setIcon(QMessageBox::Warning);
    msgBox.setText(tr("Enable Maintain Mode?"));
    msgBox.setInformativeText(tr("Enabling maintain mode (installing applications and debugging the system from arbitrary locations) may put your device and personal data at risk or cause damage to the device."));
    QPushButton *cancelBtn = msgBox.addButton(tr("Cancel"), QMessageBox::RejectRole);
    QPushButton *enableBtn = msgBox.addButton(tr("Enable"), QMessageBox::AcceptRole);
    enableBtn->setDefault(true);
    if (msgBox.exec() != QMessageBox::Accepted) {
        return false;
    } else {
        return true;
    }
}

void MaintainMode::normalExitMaintain()
{
    QVariant modeValueInConf;
    bool modeCurrentNormal, modeNextMaintain;
    modeValueInConf = readIniFile(MAINTAINMODECONF, "boot", "mode");
    modeCurrentNormal = modeValueInConf.toString() == "normal" ? true : false;
    modeValueInConf = readIniFile(MAINTAINMODECONF, "boot", "next_mode");
    modeNextMaintain = modeValueInConf.toString() == "maintain" ? true : false;

    if (modeCurrentNormal && modeNextMaintain) {
        QDBusReply<bool> reply;
        QString arg = "none";
        iface->call("CloseMaintainMode", arg);
    }
}

bool MaintainMode::mEnableButtonComfirmSlot(void)
{
    if (!iface->isValid()) {
        qDebug() << "[ERROR][Maintain Mode]DBus Interface Connect Failed...";
        return false;
    }
    if (!wmIface->isValid()) {
        qDebug() << "[ERROR][Maintain Mode][WaterMaks]DBus Interface Connect Failed...";
        return false;
    }
    QDBusReply<bool> reply;

    reply = iface->call("OpenMaintainMode");
    if (!reply.isValid()) {
        qDebug() << "[ERROR][Maintain Mode]DBus Reply(Open) is non Valid...";
        return false;
    }
    reply = wmIface->call("OpenWatermark");
    if (!reply.isValid()) {
        qDebug() << "[ERROR][Maintain Mode][WaterMaks]DBus Reply(Open) is non Valid...";
        return false;
    }

    qDebug() << "[Maintain Mode]DBus Method's reply is: " << reply.value();
    return reply.value();
}

bool MaintainMode::mEnableButtonSlot(bool status)
{
    if (!iface->isValid()) {
        qDebug() << "[ERROR][Maintain Mode]DBus Interface Connect Failed...";
        return false;
    }
    if (!wmIface->isValid()) {
        qDebug() << "[ERROR][Maintain Mode][WaterMaks]DBus Interface Connect Failed...";
        return false;
    }
    QDBusReply<bool> reply;
    if (status) {
        qDebug() << "[Debug][Maintain Mode]EnableButton Open Function is Transferring...";
        //        reply = iface->call("OpenMaintainMode");
        //        if (!reply.isValid())
        //        {
        //            qDebug() << "[ERROR][Maintain Mode]DBus Reply(Open) is non Valid...";
        //            return false;
        //        }
        //        reply = wmIface->call("OpenWatermark");
        //        if (!reply.isValid())
        //        {
        //            qDebug() << "[ERROR][Maintain Mode][WaterMaks]DBus Reply(Open) is non Valid...";
        //            return false;
        //        }
    } else {
        QDialog *dialog = new QDialog(pluginWidget);
        dialog->setWindowModality(Qt::WindowModal);
        dialog->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint);
        dialog->setAttribute(Qt::WA_TranslucentBackground); // 支持圆角透明
        dialog->setFixedSize(320, 120);
        QFrame *frame = new QFrame(dialog);
        frame->setStyleSheet("QFrame { background-color: white; border-radius: 12px; color: black; }");
        frame->setFixedSize(320, 120);
        QVBoxLayout *layout = new QVBoxLayout(frame);
        QLabel *label = new QLabel(tr("Saving maintain data,please wait..."));
        label->setAlignment(Qt::AlignCenter);
        layout->addWidget(label);
        frame->move(0, 0);
        dialog->show();
        emit inHibitChanged(true);

        QString arg = mExpandButton_1->isChecked() ? "all" : "none";
        qDebug() << "[Maintain Mode]DBus Method - CloseMaintainMode param is: " << arg;

        QDBusMessage message = QDBusMessage::createMethodCall(
            "com.kylin.MaintainMode",           // 服务名
            "/com/kylin/MaintainMode/Object",   // 对象路径
            "com.kylin.MaintainMode.interface", // 接口名
            "CloseMaintainMode"                 // 方法名
        );
        message << arg;
        QDBusPendingCall async = QDBusConnection::systemBus().asyncCall(message, MAX_SYNC_TIME);
        QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(async, this);
        QTimer::singleShot(MAX_SYNC_TIME, this, [dialog, this]() {
            emit inHibitChanged(false);
            dialog->close();
            dialog->deleteLater();
        });
        connect(watcher, &QDBusPendingCallWatcher::finished, this, [dialog, this](QDBusPendingCallWatcher *watcher) {
            QDBusPendingReply<bool> reply = *watcher;
            if (reply.isError()) {
                qDebug() << "[ERROR][Maintain Mode] CloseMaintainMode D-Bus call failed:"
                         << reply.error().name() << reply.error().message();
            } else {
                qDebug() << "[INFO][Maintain Mode] CloseMaintainMode call success, result =" << reply.value();
                if (reply.value() == true) {
                    emit inHibitChanged(false);
                    dialog->close();
                    dialog->deleteLater();
                }
            }
            watcher->deleteLater();
        });

        reply = wmIface->call("CloseWatermark");
        if (!reply.isValid()) {
            qDebug() << "[ERROR][Maintain Mode][WaterMaks]DBus Reply(Close) is non Valid...";
            qDebug() << "Error name: " << reply.error().name();
            qDebug() << "Error message: " << reply.error().message();
            return false;
        }
    }

    qDebug() << "[Maintain Mode]DBus Method's reply is: " << reply.value();
    return reply.value();
}

inline QVariant MaintainMode::readIniFile(const QString &filepath, const QString &group, const QString &key)
{
    QSettings settings(filepath, QSettings::IniFormat);
    settings.beginGroup(group);
    QVariant ans = settings.value(key);
    settings.endGroup();
    return ans;
}

void MaintainMode::mSendSignalOfWatermask()
{
    QDBusMessage WMSignal = QDBusMessage::createSignal(
        WMDBUSPATH,
        WMDBUSINTERFACE,
        WMDBUSSIGNALOFWM);
    int colorInfo = isRedButton ? 0 : 1; // need modify , not use number for dbus info !!!!!
    int sizeInfo = mFontBox->currentText() == "20" ? 20 : 30;
    int posInfo = 0;
    if (mPosisionBox->currentText() == tr("BottomRight")) {
        posInfo = 2;
    } else if (mPosisionBox->currentText() == tr("TopLeft")) {
        posInfo = 0;
    } else {
        posInfo = 1;
    }
    // int posInfo = mPosisionBox->currentText() == "左上" ? 0 : 1;
    WMSignal << colorInfo
             << sizeInfo
             << posInfo;
    if (!QDBusConnection::sessionBus().send(WMSignal)) {
        qDebug() << "[ERROR][Maintain Mode]DBus Signal of WaterMask Send Failed...";
    }
    qDebug() << "[Maintain Mode]DBus Signal of WaterMask Send Succeed!"
             << " <Color> isRed " << isRedButton
             << " <Font>" << mFontBox->currentText() << sizeInfo
             << " <Position>" << mPosisionBox->currentText() << posInfo;
}

void MaintainMode::mInhibitStatus(bool status)
{
    if (status) {
        inhibit();
    } else {
        uninhibit();
    }
}

void MaintainMode::inhibit()
{
    if (m_inhibitFileDescriptor.isValid()) {
        return;
    }

    QDBusMessage message = QDBusMessage::createMethodCall(
        "org.freedesktop.login1",
        "/org/freedesktop/login1",
        "org.freedesktop.login1.Manager",
        QStringLiteral("Inhibit"));
    message.setArguments(QVariantList({QStringLiteral("shutdown"),
                                       "Maintain Mode",
                                       "Saving data before logout or shutdown",
                                       QStringLiteral("block")}));
    QDBusPendingReply<QDBusUnixFileDescriptor> reply = QDBusConnection::systemBus().call(message);
    if (!reply.isValid()) {
        return;
    }
    reply.value().swap(m_inhibitFileDescriptor);
}

void MaintainMode::uninhibit()
{
    if (!m_inhibitFileDescriptor.isValid()) {
        return;
    }
    m_inhibitFileDescriptor = QDBusUnixFileDescriptor();
}
