#include "gui/managewidget.h"
#include "ui_managewidget.h"
#include "legacyapp.h"
#include "filesystem.h"
#include <QMessageBox>
#include <QFileDialog>

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

    uiUpdateTimer.setInterval(30);
    connect(&uiUpdateTimer, &QTimer::timeout, this, &ManageWidget::updateUI);
    uiUpdateTimer.start();
}

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

void ManageWidget::updateUI()
{
    auto res = app->client_local_dat.GetIO().GetFilename();
    if (res.result == LOTRO_DAT::SUCCESS)
        ui->datfile_name_common->setText(QString::fromStdString(res.value));
    else
        ui->datfile_name_common->setText("(файл не инициализирован)");

    if (app->client_local_dat.Initialized()) {
        ui->open_status_title->show();
        ui->close_status_title->hide();

        // Updating patched status label
        if (app->client_local_dat.GetStatusModule().CheckIfNotPatched())
            ui->not_patched_status_title->show();
        else
            ui->not_patched_status_title->hide();

        // Updating current locale status label
        if (app->client_local_dat.GetLocaleManager().GetCurrentLocale() == LOTRO_DAT::DatLocaleManager::PATCHED) {
            ui->original_locale_title->hide();
            ui->patched_locale_title->show();
        } else {
            ui->original_locale_title->show();
            ui->patched_locale_title->hide();
        }

    } else {
        ui->open_status_title->hide();
        ui->close_status_title->show();
        ui->not_patched_status_title->hide();
    }

}

void ManageWidget::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, "Расположение файла .dat", template_path, "*.dat");

    app->properties.setValue("advanced/dat_path", str);
    app->properties.sync();

    app->InitialiseDatFile();
}

void ManageWidget::on_changeLocaleButton_common_clicked()
{
    app->ChangeLocale();
}

void ManageWidget::on_createCoreStatusFile_button_common_clicked()
{
    app->CreateCoreStatusFile(app->properties.value("advanced/export_folder", "").toString());
}
