/*
 * Peony-Qt's Library
 *
 * Copyright (C) 2019, Tianjin KYLIN Information Technology Co., Ltd.
 *
 * This library 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 3 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this library.  If not, see <https://www.gnu.org/licenses/>.
 *
 * Authors: Yue Lan <lanyue@kylinos.cn>
 *
 */

#include "compatible-open-menu-plugin.h"
#include <file-info.h>
#include <stdlib.h>
#include <QAction>
#include <QUrl>
#include <QDir>
#include <QFile>
#include <QProcess>
#include <QSettings>
#include <QTextCodec>
#include <QTranslator>
#include <QLocale>
#include <QApplication>
#include <unistd.h>
#include <QDebug>
#include <QInputDialog>
#include <QMessageBox>
#include <QRegularExpression>
#include <QCryptographicHash>
#include <gio/gio.h>
#include "dialog.h"
#include <QTextStream>
#include <QString>

using namespace Peony;

CompatibleOpenMenuPlugin::CompatibleOpenMenuPlugin(QObject *parent) : QObject(parent)
{
    QTranslator *t = new QTranslator(this);
    qDebug() << "\n\n\n\n\n\n\ntranslate:" << t->load(":/translations/peony-compatible-open-extension_" + QLocale::system().name());
    QApplication::installTranslator(t);
}

QList<QAction *> CompatibleOpenMenuPlugin::menuActions(Types types, const QString &uri, const QStringList &selectionUris)
{
    qInstallMessageHandler(myMessageOutput);
    qDebug() << "DEBUG - Useless: uri - " << uri;
    QList<QAction *> actions;
    if (types == MenuPluginInterface::DirectoryView || types == MenuPluginInterface::DesktopWindow)
    {
        if (selectionUris.isEmpty())
        {
            return actions;
        }
        if (selectionUris.count() == 1)
        {
            QString decodeName = QUrl::fromPercentEncoding(selectionUris.first().toUtf8());
            if (!decodeName.startsWith("file://") || !decodeName.endsWith(".desktop"))
            {
                return actions;
            }

            QStringList decodeNameList = decodeName.split("/");
            QString desktopName = decodeNameList.last();

            bool resFlag = false;
            QDir envDir("/");
            QStringList filter;
            filter << "fs.old-*";
            QStringList envDirList = envDir.entryList(filter);
            QStringList desktopScopeList;
            for (int i = 0; i < envDirList.length(); i++)
            {
                desktopScopeList << "/" + envDirList.at(i) + "/var/cache/RevisionsManager/compat-desktops";
            }
            desktopScopeList << "/usr/share/kylin-os-manager/replacement/desktop.list";
            for (int j = 0; j < desktopScopeList.length(); j++)
            {
                QString desktopScope = desktopScopeList.at(j);
                QFile file(desktopScope);
                if (!file.open(QIODevice::ReadOnly))
                {
                    qDebug() << "WARNING - Failed to Open Compatible/HJZS App Desktop List = " << desktopScope;
                }
                else
                {
                    QTextStream in(&file);
                    while (!in.atEnd())
                    {
                        QString line = in.readLine();
                        if (line.contains(desktopName))
                        {
                            resFlag = true;
                            break;
                        }
                    }
                }
            }
            if (!resFlag)
            {
                qDebug() << "WARNING - 该应用不属于兼容应用/换机应用,不支持右键兼容打开";
                return actions;
            }
            QString desktopPath = decodeName.remove("file://");
            qDebug() << "DEBUG - desktopPath: " << decodeName;

            // 读取desktop文件
            QSettings ini(desktopPath, QSettings::IniFormat);
            ini.setIniCodec(QTextCodec::codecForName("UTF8"));

            // 取 Exec 值
            QString execValue = ini.value("Desktop Entry/Exec").toString();
            qDebug() << "DEBUG - execValue: " << execValue;

            QString execOrigin = execValue;
            // 处理execValue，如果是兼容修改，则提取原Exec值
            if (execValue.startsWith("/bin/bash /usr/bin/runWithCompatibility.sh "))
            {
                execOrigin = execValue.remove("/bin/bash /usr/bin/runWithCompatibility.sh ");
                qDebug() << "DEBUG - 去除兼容指令后Exec: " << execOrigin;
            }
            else if (execValue.startsWith("kare run "))
            {
                execOrigin = execValue.remove("kare run ");
                qDebug() << "DEBUG - 去除兼容指令后Exec: " << execOrigin;
            }

            if (execOrigin.startsWith("bash "))
            {
                execOrigin = execOrigin.remove("bash ");
            }
            else if (execValue.startsWith("/bin/bash "))
            {
                execOrigin = execOrigin.remove("/bin/bash ");
            }
            else if (execValue.startsWith("/usr/bin/bash "))
            {
                execOrigin = execOrigin.remove("/usr/bin/bash ");
            }
            else if (execValue.startsWith("sh "))
            {
                execOrigin = execOrigin.remove("sh ");
            }
            else if (execValue.startsWith("/bin/sh "))
            {
                execOrigin = execOrigin.remove("/bin/sh ");
            }
            else if (execValue.startsWith("/usr/bin/sh "))
            {
                execOrigin = execOrigin.remove("/usr/bin/sh ");
            }
            qDebug() << "DEBUG - 去除前缀后Exec: " << execOrigin;
            
            QStringList execPart = execOrigin.split("/");
            QString execAidPart = execPart.last();
            QStringList aidPart = execAidPart.split(" ");
            QString execKernel = aidPart.first();
            qDebug() << "DEBUG - execKernel: " << execKernel;

            QString clConfIni = "/opt/compatibility_layer/config/configure.ini";
            QSettings confIni(clConfIni, QSettings::IniFormat);
            confIni.setIniCodec(QTextCodec::codecForName("UTF8"));
            QString upgradeSceneFlag = confIni.value("Scene/upgrade").toString();

            QAction *dirAction = new QAction(QIcon::fromTheme("xjump"), tr("Open in Compatible Mode"), nullptr);
            dirAction->connect(dirAction, &QAction::triggered, [ = ]()
            {
                Dialog *dialog = new Dialog(execKernel, nullptr);
                QString selectedOption = "Ubuntu22.04";
                if (dialog->exec() == QDialog::Accepted)
                {
                    selectedOption = dialog->getItem();
                    dialog->storePrefer();
                }
                else
                {
                    qDebug() << "DEBUG - 用户点击了取消按钮或关闭了对话框";
                    return;
                }
                qDebug() << "DEBUG - 用户最终选择的兼容环境为: " << selectedOption;
                if (!selectedOption.isEmpty())
                {
                    // // 将 Exec 转 md5 值，作为容器名称
                    // QCryptographicHash hash(QCryptographicHash::Md5);
                    // QString containerNameStr = execOrigin + selectedOption;
                    // hash.addData(containerNameStr.toUtf8());
                    // QString appName = hash.result().toHex();
                    // qDebug() << "DEBUG - dockerContainerName: " << appName;

                    QProcess *process = new QProcess;
                    //    QString compatibility_tool = "bwrap";
                    //    GSettings *gs = NULL;
                    //    char *keyvalue;
                    //    gs = g_settings_new("org.kylin.compatible-layer");
                    //    if (!gs)
                    //    {
                    //        qDebug() << "WARNING - 不存在兼容层Gsettings配置文件";
                    //    }
                    //    else
                    //    {
                    //        keyvalue = g_settings_get_string(gs, "method");
                    //        compatibility_tool = QString(keyvalue);
                    //    }
                    //    g_object_unref(gs);
                    //    qDebug() << "DEBUG - 获取到的兼容层方法为:" << compatibility_tool;
                    QString main = "kare run " + execOrigin + " ";
                    main += selectedOption;
                    main += " rightclick";
                    qDebug() << "DEBUG - Main: " << main;
                    process->start(main);
                    if (!process->waitForStarted())
                    {
                        qDebug() << "ERROR - 兼容模式不能启动";
                        process->kill();
                        process = nullptr;
                        delete process;
                        return;
                    }
                }
                else
                {
                    QMessageBox::warning(nullptr, "警告", "请选择兼容环境", QMessageBox::Ok);
                    return;
                }
            });
            actions << dirAction;
        }
    }
    return actions;
}
