#include "adddesktop.h"
#include "ui_adddesktop.h"
#include <QTextStream>
#include <fstream>
#include <of_str.h>

using namespace ofen;

AddDesktop::AddDesktop(QWidget* parent) : QDialog(parent), ui(new Ui::AddDesktop)
{
    ui->setupUi(this);

    setWindowTitle("添加到菜单");

    // Audio:音频应用程序,如播放器、编辑器等。
    // Video:视频应用程序,如播放器、编辑器等。
    // Development:开发工具,如IDE、编辑器等。
    // Education:教育类应用程序,如学习工具、教育游戏等。
    // Game:游戏应用程序。
    // Graphics:图形设计和编辑工具。
    // Office:办公软件,如文档编辑器、电子表格、演示文稿等。
    // Science:科学工具和应用程序,如数学、物理学、化学工具等。
    // Settings:系统设置工具。
    // System:系统工具,如文件管理器、终端模拟器等。
    // Utility:实用工具,如压缩软件、文本编辑器等。

    ui->cbCategories->addItem("Audio");
    ui->cbCategories->addItem("Video");
    ui->cbCategories->addItem("Development");
    ui->cbCategories->addItem("Education");
    ui->cbCategories->addItem("Game");
    ui->cbCategories->addItem("Graphics");
    ui->cbCategories->addItem("Office");
    ui->cbCategories->addItem("Science");
    ui->cbCategories->addItem("Settings");
    ui->cbCategories->addItem("Utility");
    ui->cbCategories->setCurrentIndex(ui->cbCategories->count() - 1);

    connect(ui->ckUseDefault, &QCheckBox::toggled, this, &AddDesktop::checkchange);
    connect(ui->btnSelectBinary, &QPushButton::clicked, this,
            [=]() { MainWidget::SelectFile(this, ui->edBinary, "请选择二进制文件", "所有文件 (*)"); });
    connect(ui->btnSelectIco, &QPushButton::clicked, this, [=]() {
        MainWidget::SelectFile(this, ui->edIco, "请选择ico图标文件",
                               "png图标(*.png);;ico图标(*.ico);;svg图标(*.svg);;所有文件 (*)");
    });
    connect(ui->btnInstall, &QPushButton::clicked, this, &AddDesktop::install_to_desktop);
    connect(ui->envAdd, &QPushButton::clicked, this, &AddDesktop::add_env_btn);
    connect(ui->envDel, &QPushButton::clicked, this, &AddDesktop::del_env_btn);
}

void AddDesktop::checkchange()
{
    if (ui->ckUseDefault->isChecked()) {
        ui->edIco->setEnabled(false);
        ui->btnSelectIco->setEnabled(false);
    } else {
        ui->edIco->setEnabled(true);
        ui->btnSelectIco->setEnabled(true);
    }
}

void AddDesktop::install_to_desktop()
{
    QFile file("://resource/desktop.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return;
    }

    std::string binaryPath = ui->edBinary->text().trimmed().toStdString();
    if (binaryPath.empty()) {
        MainWidget::message(this, "二进制路径为空");
        return;
    }
    std::string binaryName = fs::path(binaryPath).filename().string();
    fs::path sh_path = fs::path(binaryPath).parent_path().append(binaryName + ".sh");

    std::string cmodBin = "chmod +x " + binaryPath;
    std::string cmodSh = "chmod +x " + sh_path.string();
    MainWidget::cmd_exec(cmodBin);
    MainWidget::cmd_exec(cmodSh);

    if (!fs::exists(sh_path)) {
        MainWidget::add_run_sh(sh_path.parent_path().string(), binaryName);
    }
    fs::path tmp = fs::path(QDir::homePath().toStdString()).append(".config");
    if (!fs::exists(tmp)) {
        fs::create_directories(tmp);
    }

    QTextStream stream(&file);
    QString content = stream.readAll();
    file.close();
    std::string ct = content.toStdString();
    ct = COfStr::replace(ct, "re_name", binaryName);
    ct = COfStr::replace(ct, "re_describe", binaryName);
    ct = COfStr::replace(ct, "re_path", "sh " + sh_path.string());

    fs::path default_ico_path = fs::path(tmp).append("packqt");
    if (!fs::exists(default_ico_path)) {
        fs::create_directories(default_ico_path);
    }
    if (ui->ckUseDefault->isChecked()) {
        default_ico_path.append("Tools.svg");
        QFile::copy("://resource/Tools.svg", QString::fromStdString(default_ico_path.string()));
        ct = COfStr::replace(ct, "re_icon", default_ico_path.string());

    } else {
        std::string icn = ui->edIco->text().trimmed().toStdString();
        if (icn.empty()) {
            MainWidget::message(this, "图标路径为空");
            return;
        }
        default_ico_path.append(fs::path(icn).filename().string());
        ct = COfStr::replace(ct, "re_icon", default_ico_path.string());
        fs::copy_file(icn, default_ico_path, fs::copy_options::overwrite_existing);
    }

    ct = COfStr::replace(ct, "re_category", ui->cbCategories->currentText().toStdString());
    tmp.append(binaryName + ".desktop");
    ;
    std::ofstream out(tmp.string(), std::ios::out);
    if (!out.is_open()) {
        return;
    }
    out << ct;
    out.close();
    std::string cp_cmd("pkexec cp " + tmp.string() + " /usr/share/applications");
    MainWidget::cmd_exec(cp_cmd);
    fs::remove(tmp);
    MainWidget::message(this, "完成");
}

AddDesktop::~AddDesktop()
{
    delete ui;
}

void AddDesktop::add_env_btn()
{
    QString env = MainWidget::SelectDirectory(this, nullptr);
    if (env.isEmpty()) {
        return;
    }
    ui->listWidget->addItem(env);
}

void AddDesktop::del_env_btn()
{
    QListWidgetItem* item = ui->listWidget->currentItem();
    if (!item) {
        return;
    }
    delete ui->listWidget->takeItem(ui->listWidget->currentRow());
}