#include "startup_app_edit.h"
#include "ui_startup_app_edit.h"
#include "utilities.h"

#include <QRegularExpression>
#include <QScreen>
#include <QStyle>

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

QString StartupAppEdit::selectedFilePath = "";

StartupAppEdit::StartupAppEdit(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::StartupAppEdit),
    mNewAppTemplate("[Desktop Entry]\n"
                    "Type=Application\n"
                    "Name=%1\n"
                    "GenericName=%2\n"
                    "Comment=%3\n"
                    "Icon=%4\n"
                    "Hidden=false\n"
                    "Exec=%5\n"
                    "Terminal=false\n"
                    "X-GNOME-Autostart-enabled=true\n"
                    "X-GNOME-Autostart-Delay=5\n")
{
    ui->setupUi(this);

    init();
}

void StartupAppEdit::init()
{
    setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, size(),
                                    qApp->primaryScreen()->availableGeometry()));

    mAutostartPath = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + "/autostart";

    ui->lblErrorMsg->hide();

    setStyleSheet(AppManager::ins()->getStylesheetFileContent());
}

void StartupAppEdit::show()
{
    // clear fields
    ui->txtStartupAppName->clear();
    ui->txtStartupAppGenericName->clear();
    ui->txtStartupAppComment->clear();
    ui->txtStartupAppIcon->clear();
    ui->txtStartupAppCommand->clear();
    ui->lblErrorMsg->hide();

    if (!selectedFilePath.isEmpty()) {
        QStringList lines = FileUtil::readListFromFile(selectedFilePath);

        if (!lines.isEmpty()) {
            ui->txtStartupAppName->setText(Utilities::getDesktopValue(NAME_REG, lines));
            ui->txtStartupAppGenericName->setText(Utilities::getDesktopValue(GENERIC_NAME_REG, lines));
            ui->txtStartupAppComment->setText(Utilities::getDesktopValue(COMMENT_REG, lines));
            ui->txtStartupAppIcon->setText(Utilities::getDesktopValue(ICON_REG, lines));
            ui->txtStartupAppCommand->setText(Utilities::getDesktopValue(EXEC_REG, lines));
        }
    }

    QDialog::show();
}

void StartupAppEdit::changeDesktopValue(QStringList &lines, const QRegularExpression &reg, const QString &text)
{
    int pos = lines.indexOf(reg);

    if (pos != -1) {
        lines.replace(pos, text);
    } else {
        lines.append(text);
    }
}

void StartupAppEdit::on_btnSave_clicked()
{
    if (isValid()) {
        if (!selectedFilePath.isEmpty()) {
            QStringList lines = FileUtil::readListFromFile(selectedFilePath);

            changeDesktopValue(lines, NAME_REG, QString("Name=%1").arg(ui->txtStartupAppName->text()));
            changeDesktopValue(lines, GENERIC_NAME_REG, QString("GenericName=%1").arg(ui->txtStartupAppGenericName->text()));
            changeDesktopValue(lines, COMMENT_REG, QString("Comment=%1").arg(ui->txtStartupAppComment->text()));
            changeDesktopValue(lines, ICON_REG, QString("Icon=%1").arg(ui->txtStartupAppIcon->text()));
            changeDesktopValue(lines, EXEC_REG, QString("Exec=%1").arg(ui->txtStartupAppCommand->text()));

            FileUtil::writeFile(selectedFilePath, lines.join("\n"), QIODevice::ReadWrite | QIODevice::Truncate);
        } else {
            // new file content
            QString appContent = mNewAppTemplate
                                     .arg(ui->txtStartupAppName->text())
                                     .arg(ui->txtStartupAppGenericName->text())
                                     .arg(ui->txtStartupAppComment->text())
                                     .arg(ui->txtStartupAppIcon->text())
                                     .arg(ui->txtStartupAppCommand->text());

            // file name
            QString appFileName = ui->txtStartupAppName->text()
                                      .simplified()
                                      .replace(' ', '-')
                                      .toLower();

            QString path = QString("%1/%2.desktop").arg(mAutostartPath).arg(appFileName);

            FileUtil::writeFile(path, appContent);
        }

        emit startupAppAdded(); // signal
        close();
    } else {
        ui->lblErrorMsg->show();
    }

    selectedFilePath = "";
}

bool StartupAppEdit::isValid()
{
    return !ui->txtStartupAppName->text().isEmpty() &&
           !ui->txtStartupAppCommand->text().isEmpty();
}
