/*
Copyright (c) 2006-2009, Tom Thielicke IT Solutions
Copyright (c) 2021, André Apitzsch

SPDX-License-Identifier: GPL-2.0-only
*/

#include "regexpdialog.h"
#include "ui_regexpdialog.h"

#include <QPushButton>
#include <QSettings>

#include "sql/trainingsql.h"

RegExpDialog::RegExpDialog(QString layout, QWidget* parent)
    : QDialog(parent)
    , ui(new Ui::RegExpDialog)
    , currentLayout(layout)
{
    ui->setupUi(this);

    readSettings();

    QPushButton* resetButton
        = ui->buttonBox->button(QDialogButtonBox::RestoreDefaults);
    connect(
        resetButton, &QPushButton::clicked, this, &RegExpDialog::getDefault);

    connect(
        ui->buttonBox, &QDialogButtonBox::accepted, this, &RegExpDialog::save);
}

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

void RegExpDialog::save()
{
    writeSettings();
    this->accept();
}

void RegExpDialog::getDefault()
{
    TrainingSql* trainingSql = new TrainingSql();
    ui->lineRegExp->setText(
        trainingSql->getKeyboardLayoutRegexpRoutine(currentLayout));
    ui->lineReplace->setText(
        trainingSql->getKeyboardLayoutReplaceRoutine(currentLayout));
}

void RegExpDialog::readSettings()
{
#if APP_PORTABLE
    QSettings settings(
        QCoreApplication::applicationDirPath() + "/portable/settings.ini",
        QSettings::IniFormat);
#else
    QSettings settings;
#endif
    settings.beginGroup("main");
    QString regexp = settings.value("layout_regexp", "NULL").toString();
    QString replace = settings.value("layout_replace", "NULL").toString();
    settings.endGroup();
    TrainingSql* trainingSql = new TrainingSql();

    if (regexp == "NULL") {
        regexp = trainingSql->getKeyboardLayoutRegexpRoutine(currentLayout);
    }
    if (replace == "NULL") {
        replace = trainingSql->getKeyboardLayoutReplaceRoutine(currentLayout);
    }
    ui->lineRegExp->setText(regexp);
    ui->lineReplace->setText(replace);
}

void RegExpDialog::writeSettings()
{
#if APP_PORTABLE
    QSettings settings(
        QCoreApplication::applicationDirPath() + "/portable/settings.ini",
        QSettings::IniFormat);
#else
    QSettings settings;
#endif
    settings.beginGroup("main");
    settings.setValue("layout_replace", ui->lineReplace->text());
    settings.setValue("layout_regexp", ui->lineRegExp->text());
    settings.endGroup();
}
