/*
 * Copyright (C) 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, 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 <QtWidgets>

#include "display.h"
#include "ui_display.h"
#include "ukcccommon.h"
using namespace ukcc;

#include <KF5/KScreen/kscreen/getconfigoperation.h>
#include <KF5/KScreen/kscreen/output.h>
#include <QDebug>
#include <QDBusInterface>
#include <QDBusConnection>
#include <QProcess>
#include <QDir>

DisplaySet::DisplaySet() : mFirstLoad(true)
{
#ifdef MAVIS
    pluginName = tr("Screen");
#else
    pluginName = tr("Display");
#endif
    pluginType = SYSTEM;
}

DisplaySet::~DisplaySet()
{
    if (pluginWidget) {
        delete pluginWidget;
        pluginWidget = nullptr;
    }
}

QWidget *DisplaySet::pluginUi()
{
    if (mFirstLoad) {
        requestBackend();
        mFirstLoad = false;
        pluginWidget = new QWidget;
    }

    // 检查lxrandr进程是否已经存在
    if (!isProcessRunning("lxrandr")) {
        QProcess::startDetached("lxrandr");
    }
    return pluginWidget;
}

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

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

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

bool DisplaySet::isShowOnHomePage() const
{
    return true;
}

QIcon DisplaySet::icon() const
{
    return QIcon::fromTheme("system-computer-symbolic");
}

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

void DisplaySet::requestBackend()
{
    QDBusInterface screenIft("org.kde.KScreen",
                             "/",
                             "org.kde.KScreen",
                             QDBusConnection::sessionBus());
    if (!screenIft.isValid()) {
        QProcess process;
        process.start("uname -m");
        process.waitForFinished();
        QString output = process.readAll();
        output = output.simplified();

        QString command = "/usr/lib/" + output + "-linux-gnu"
                          +"/libexec/kf5/kscreen_backend_launcher";
        QProcess::startDetached(command);
    }
}

bool DisplaySet::isProcessRunning(const QString &processName)
{
    QDir procDir("/proc");
    QStringList pidDirs = procDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);

    for (const QString &pidDir : pidDirs) {
        // 检查是否为数字目录（PID）
        bool isPid;
        pidDir.toInt(&isPid);
        if (!isPid) continue;

        QString commPath = QString("/proc/%1/comm").arg(pidDir);
        QFile commFile(commPath);

        if (commFile.open(QIODevice::ReadOnly)) {
            QByteArray commData = commFile.readAll();
            commFile.close();

            QString comm = QString::fromUtf8(commData).trimmed();
            if (comm == processName) {
                return true;
            }
        }
    }

    return false;
}
