#include "widgets/settingswidget.h"
#include "widgets/mainwindow.h"
#include "ui_settingswidget.h"
#include "models/filesystem.h"
#include "models/lotrodatmanager.h"
#include "models/patchdownloader.h"
#include "constants.h"

#include <QDebug>
#include <QScrollBar>
#include <QFileDialog>
#include <QMetaObject>

SettingsWidget::SettingsWidget(QSettings* settings, PatchDownloader* patch_downloader, LotroDatManager* lotro_dat_manager, QWidget *parent) :
    QWidget(parent), app_settings(settings), patch_updater(patch_downloader), lotro_manager(lotro_dat_manager),
    ui(new Ui::SettingsWidget)
{
    ui->setupUi(this);
    for (int i = 1; i <= 4; ++i)
        setStatusToBlock(i, E_ERROR);

    combobox_scrolling_disabler = new SettingsWidgetPrivate::ComboboxScrollingDisabler();

    ui->lotro_base_language_combobox->installEventFilter(combobox_scrolling_disabler);
    ui->interface_scale_combobox->installEventFilter(combobox_scrolling_disabler);

    connect(patch_downloader, &PatchDownloader::checkForUpdatesStarted, this, &SettingsWidget::handleCheckForUpdatesStarted, Qt::QueuedConnection);
    connect(patch_downloader, &PatchDownloader::checkForUpdatesFinished, this, &SettingsWidget::handleCheckForUpdatesFinished, Qt::QueuedConnection);
    connect(lotro_manager, &LotroDatManager::processStarted, this, &SettingsWidget::handleLotroManagerStarted);
    connect(lotro_manager, &LotroDatManager::processFinished, this, &SettingsWidget::handleLotroManagerFinished);

}

SettingsWidget::~SettingsWidget()
{
    delete combobox_scrolling_disabler;
    delete ui;
}

void SettingsWidget::updateFontsSizes()
{
    ui->frame_title->setFont(trajan_10pt);
    ui->group_label_1->setFont(trajan_8pt);
    ui->group_label_2->setFont(trajan_8pt);
    ui->group_label_3->setFont(trajan_8pt);
    ui->group_label_4->setFont(trajan_8pt);

    ui->sub_entry_1_title->setFont(garamond_11pt);
    ui->sub_entry_2_title->setFont(garamond_11pt);
    ui->sub_entry_3_title->setFont(garamond_11pt);
    ui->sub_entry_4_title->setFont(garamond_11pt);

    ui->backup_create_button->setFont(trajan_8pt);
    ui->backup_restore_button->setFont(trajan_8pt);
    ui->backup_remove_button->setFont(trajan_8pt);
    ui->reinstall_rusification_button->setFont(trajan_8pt);

    ui->patch_apply_button->setFont(trajan_11pt);

    ui->game_folder_label->setFont(crimson_11pt);
    ui->game_folder_path->setFont(crimson_11pt);
    ui->lotro_base_language_label->setFont(crimson_11pt);
    ui->lotro_base_language_combobox->setFont(crimson_11pt);
    ui->lotro_base_language_combobox->insertItem(ui->lotro_base_language_combobox->count(), ""); // is needed to invoke elements resize
    ui->lotro_base_language_combobox->removeItem(ui->lotro_base_language_combobox->count() - 1);

    ui->skiprawdownload_checkbox->setFont(crimson_11pt);
    ui->nosplashscreen_checkbox->setFont(crimson_11pt);
    ui->backup_status_label->setFont(crimson_11pt);
    ui->backup_status_value->setFont(crimson_11pt);
    ui->backup_creation_time_label->setFont(crimson_11pt);
    ui->backup_creation_time_value->setFont(crimson_11pt);
    ui->backup_path_label->setFont(crimson_11pt);
    ui->backup_path_value->setFont(crimson_11pt);

    ui->patch_emotes_checkbox->setFont(crimson_11pt);
    ui->patch_fonts_checkbox->setFont(crimson_11pt);
    ui->patch_items_checkbox->setFont(crimson_11pt);
    ui->patch_loadscreens_checkbox->setFont(crimson_11pt);
    ui->patch_maps_checkbox->setFont(crimson_11pt);
    ui->patch_sounds_checkbox->setFont(crimson_11pt);
    ui->patch_textures_checkbox->setFont(crimson_11pt);
    ui->patch_video_checkbox->setFont(crimson_11pt);
    ui->patch_texts_checkbox->setFont(crimson_11pt);

    ui->micropatch_checkbox->setFont(crimson_11pt);
    ui->interface_scale_label->setFont(crimson_11pt);
    ui->interface_scale_combobox->setFont(crimson_11pt);
    ui->interface_scale_combobox->insertItem(ui->interface_scale_combobox->count(), "250%"); // is needed to invoke elements resize
    ui->interface_scale_combobox->removeItem(ui->interface_scale_combobox->count() - 1);

    ui->texts_block_label->setFont(crimson_12pt);
    ui->graphics_block_label->setFont(crimson_12pt);
    ui->sounds_block_label->setFont(crimson_12pt);
}

void SettingsWidget::setStatusToBlock(int block_id, SettingsWidget::E_STATUS status)
{
    QWidget* widget = ui->checkpoints_list->findChild<QWidget*>("group_status_icon_" + QString::number(block_id));
    if (!widget)
        return;

    if (status == E_NONE)
        widget->setStyleSheet("");
    if (status == E_OK)
        widget->setStyleSheet("border-image: url(:/status/ok_icon.png);");
    if (status == E_WARNING)
        widget->setStyleSheet("border-image: url(:/status/alert_icon.png);");
    if (status == E_ERROR)
        widget->setStyleSheet("border-image: url(:/status/error_icon.png);");
}

void SettingsWidget::resizeEvent(QResizeEvent *event)
{
    updateFontsSizes();
    double coefficient = window_width / default_window_width;

    ui->frame_title->move(QPoint(45, 33) * coefficient);
    ui->frame_title->resize(QSize(201, 21) * coefficient);
    ui->checkpoints_list->move(QPoint(25, 70) * coefficient);
    ui->checkpoints_list->resize(QSize(265, 321) * coefficient);
    ui->content_scroll_area->move(QPoint(310, 0) * coefficient);
    ui->content_scroll_area->resize(QSize(671, 521) * coefficient);

    ui->group_status_icon_1->setMinimumSize(QSize(25, 25) * coefficient);
    ui->group_status_icon_2->setMinimumSize(QSize(25, 25) * coefficient);
    ui->group_status_icon_3->setMinimumSize(QSize(25, 25) * coefficient);
    ui->group_status_icon_4->setMinimumSize(QSize(25, 25) * coefficient);

    ui->change_folder_button->setMinimumSize(QSize(36, 32) * coefficient);

    ui->patch_texts_icon->setMinimumSize(QSize(80, 80) * coefficient);
    ui->patch_graphics_icon->setMinimumSize(QSize(80, 80) * coefficient);
    ui->patch_sounds_icon->setMinimumSize(QSize(80, 80) * coefficient);
    ui->patch_apply_button->setMinimumHeight(double(55) * coefficient);
}

void SettingsWidget::handleLotroManagerStarted(QString process_name, QVector<QVariant> data)
{
}

void SettingsWidget::handleLotroManagerFinished(QString process_name, QVector<QVariant> data)
{
//    if (process_name == "")
}

void SettingsWidget::handleCheckForUpdatesStarted()
{

}

void SettingsWidget::handleCheckForUpdatesFinished()
{

}

void SettingsWidget::on_interface_scale_combobox_currentIndexChanged(const QString &arg1)
{
    MainWindow* window = qobject_cast<MainWindow*>(qApp->activeWindow());

    if (!window) {
        ui->interface_scale_combobox->setCurrentText(app_settings->value("general/ui_scale", 100).toString() + "%");
        qDebug() << "CANNOT FIND MAIN WINDOW!!!";
        return;
    }

    int value = arg1.left(arg1.length() - 1).toInt();
    window->resize(1000 * value / 100, 648 * value / 100);
    app_settings->setValue("general/ui_scale", value);
}

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

    if (app_settings->value("General/game_folder_path", "").toString() == game_folder)
        return;

    app_settings->setValue("General/game_folder_path", game_folder);
    ui->game_folder_path->setText(game_folder);
    QMetaObject::invokeMethod(lotro_manager, "InitialiseManager", Qt::QueuedConnection);
}

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

    if (app_settings->value("General/original_locale", "").toString() == value)
        return;

    app_settings->setValue("General/original_locale", value);
    QMetaObject::invokeMethod(lotro_manager, "InitialiseManager", Qt::QueuedConnection);
}
