#include "gui\settingswidget.h"
#include "ui_settingswidget.h"
#include "legacyapp.h"
#include "filesystem.h"

#include <QDebug>
#include <QFileDialog>
#include <QMessageBox>


SettingsWidget::SettingsWidget(LegacyApp *_app, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SettingsWidget),
    app(_app)
{
    ui->setupUi(this);

    ui_update_timer.setInterval(500);
    connect(&ui_update_timer, &QTimer::timeout, this, &SettingsWidget::updateUI);
    ui_update_timer.start();
}

SettingsWidget::~SettingsWidget()
{
    ui_update_timer.stop();
    delete ui;
}

void SettingsWidget::updateUI()
{
    if (!qApp)
        return;

    QString path = app->properties.value("settings/lotro_folder", "(не выбрана)").toString();
    ui->folder_value_common->setText(path);

    ui->data_protection_checkbox_common->setChecked(app->properties.value("settings/data_protection", 1).toBool());
    ui->restore_checkbox_common->setChecked(app->properties.value("settings/auto_restore", 1).toBool());
    ui->download_updates_checkbox_common->setChecked(app->properties.value("settings/download_updates", 1).toBool());
    ui->expert_tabs_checkbox_common->setChecked(app->properties.value("settings/expert_mode", 0).toBool());
    ui->restrict_download_speed_checkbox_common->setChecked(app->properties.value("settings/limit_download_speed", 0).toBool());
    ui->download_restrict_slider->setValue(app->properties.value("settings/download_speed", 64).toInt());

    if (app->properties.value("settings/expert_mode", 0).toBool()) {
        ui->management_widget->show();
        ui->data_protection_checkbox_common->show();
        ui->restore_checkbox_common->show();
    } else {
        ui->management_widget->hide();
        ui->data_protection_checkbox_common->hide();
        ui->restore_checkbox_common->hide();
    }

    int locale_index = 0;
    QString value = app->properties.value("settings/locale", "English").toString();

    if (value == "English")
        locale_index = 0;
    if (value == "DE")
        locale_index = 1;
    if (value == "FR")
        locale_index = 2;

    ui->lotro_patch_language_combobox_common->setCurrentIndex(locale_index);
}

void SettingsWidget::on_download_restrict_slider_valueChanged(int value)
{
    if (value >= 1024) {
        double new_value = double(value) / 1024;
        ui->download_speed_label_common->setText(QString::number(new_value, 'g', 2) + " Мб/с");
    } else {
        ui->download_speed_label_common->setText(QString::number(value) + " Кб/с");
    }
    app->properties.setValue("settings/download_speed", value);
    app->properties.sync();
}

void SettingsWidget::on_interface_scale_combobox_common_currentIndexChanged(const QString &arg1)
{
    int value = arg1.left(arg1.length() - 1).toInt();
    app->window.changeFontSizeRecursive(value, &app->window);
    app->window.resize(900 * value / 100, 650 * value / 100);
    app->properties.setValue("settings/ui_scale", value);
    app->properties.sync();
}

void SettingsWidget::on_change_folder_button_clicked()
{
    QStringList known_paths = FileSystem::recognizeRegistryLotroPath();
    QString template_path = known_paths.size() > 0 ? known_paths[0] : "";
    QString str = QFileDialog::getOpenFileName(0, "Расположение игры", template_path, "LotroLauncher.exe");
    QString path = str.replace("/LotroLauncher.exe", "").replace("\\", "/").replace("//", "/");

    if (!FileSystem::fileExists(path + "/LotroLauncher.exe")) {
        QMessageBox error_box("Ошибка!", "Похоже, указана неверная папка с игрой. Не могу найти файл LotroLauncher.exe",
                              QMessageBox::Critical, QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton);

        return;
    }

    if (!FileSystem::fileExists(path + "/client_local_English.dat")) {
        QMessageBox pmbx("Файл данных не найден",
                         "Файл данных client_local_English.dat не обнаружен в папке с игрой. Запустить лаунчер игры с целью скачать недостающие данные?",
                         QMessageBox::Warning,
                         QMessageBox::Yes,
                         QMessageBox::No,
                         QMessageBox::NoButton);

        if (pmbx.exec() == QMessageBox::Yes) {
            // Start LotRO;
            return;
        } else {
            // Set status Файл данных не найден
        }
    }

    app->properties.setValue("settings/lotro_folder", path);
    app->properties.sync();
    ui->folder_value_common->setText(path);
}

void SettingsWidget::on_data_protection_checkbox_common_stateChanged(int arg1)
{
    app->properties.setValue("settings/data_protection", arg1);
    app->properties.sync();
}

void SettingsWidget::on_restore_checkbox_common_stateChanged(int arg1)
{
    app->properties.setValue("settings/auto_restore", arg1);
    app->properties.sync();
}

void SettingsWidget::on_download_updates_checkbox_common_stateChanged(int arg1)
{
    app->properties.setValue("settings/download_updates", arg1);
    app->properties.sync();
}

void SettingsWidget::on_expert_tabs_checkbox_common_stateChanged(int arg1)
{
    app->properties.setValue("settings/expert_mode", arg1);
    app->properties.sync();
}

void SettingsWidget::on_restrict_download_speed_checkbox_common_stateChanged(int arg1)
{
    app->properties.setValue("settings/limit_download_speed", arg1);
    app->properties.sync();
}


void SettingsWidget::on_lotro_patch_language_combobox_common_activated(int index)
{
    QString value = "";
    if (index == 0)
        value = "English";
    if (index == 1)
        value = "DE";
    if (index == 2)
        value = "FR";

    app->properties.setValue("settings/locale", value);
    app->properties.sync();
}
