#include "managewidget.h"
#include "ui_managewidget.h"
#include "models/lotrodatmanager.h"
#include "models/filesystem.h"
#include "widgets/mainwindow.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QDebug>

ManageWidget::ManageWidget(LotroDatManager* mgr, QSettings* settings, QWidget *parent) :
    QWidget(parent), lotro_manager(mgr), settings(settings), ui(new Ui::ManageWidget)
{
    ui->setupUi(this);
    connect(lotro_manager, &LotroDatManager::processFinished, this, &ManageWidget::onLotroManagerProcessFinished, Qt::QueuedConnection);
    connect(lotro_manager, &LotroDatManager::unactiveCategoriesReceived, this, &ManageWidget::onLotroManagerInactiveCateroiesListUpdated);
}

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

void ManageWidget::updateUI()
{
    if (lotro_manager->initialised()) {
        ui->open_status_title->show();
        ui->close_status_title->hide();
        ui->initButton_common->hide();
        ui->deinitButton_common->show();

        ui->changeLocaleButton_common->setEnabled(true);
        ui->createCoreStatusFile_button_common->setEnabled(true);
        ui->activate_category_button->setEnabled(true);
        ui->deactivate_category_button->setEnabled(true);

        emit enableMenuItems();

        // Updating patched status label
        if (lotro_manager->notPatched())
            ui->not_patched_status_title->show();
        else
            ui->not_patched_status_title->hide();

        // Updating current locale status label
        if (lotro_manager->currentLocale() == int(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->initButton_common->show();
        ui->deinitButton_common->hide();

        ui->changeLocaleButton_common->setEnabled(false);
        ui->createCoreStatusFile_button_common->setEnabled(false);
        ui->activate_category_button->setEnabled(false);
        ui->deactivate_category_button->setEnabled(false);

        emit disableMenuItems();

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

void ManageWidget::onLotroManagerProcessFinished(QString proc_name, QVector<QVariant> data) {
    if (proc_name == "initialiseDatFile" && data[0].toString() == "Success") {
        settings->setValue("advanced/dat_path", data[1].toString());
        settings->sync();
        ui->datfile_name_common->setText(data[1].toString());
    }

    if (proc_name == "initialiseDatFile" && data[0].toString() == "Error") {
        settings->setValue("advanced/dat_path", "");
        settings->sync();
        ui->datfile_name_common->setText("Ошибка инициализации, файл не выбран");
    }

    updateUI();
}

void ManageWidget::onLotroManagerInactiveCateroiesListUpdated(QStringList categories)
{
    if (categories.empty())
        ui->inactive_categories_list->setText("(нет)");
    else
        ui->inactive_categories_list->setText(categories.join(", "));
}

void ManageWidget::on_change_folder_button_clicked()
{
    QStringList known_paths = FileSystem::recognizeRegistryLotroPath();
    QString template_path = known_paths.size() > 0 ? known_paths[0] : "";
    QString fileName = QFileDialog::getOpenFileName(0, "Расположение файла .dat", template_path, "Файлы ресурсов (*.dat *.datx)");

    if (fileName.isEmpty())
            return;

    QMetaObject::invokeMethod(lotro_manager, "initialiseDatFile", Qt::QueuedConnection,
                              Q_ARG(QString, fileName));
}

void ManageWidget::on_changeLocaleButton_common_clicked()
{
    QMetaObject::invokeMethod(lotro_manager, "changeLocale", Qt::QueuedConnection);
}

void ManageWidget::on_createCoreStatusFile_button_common_clicked()
{
    QString fileName = QFileDialog::getSaveFileName(this->parentWidget(), "Сохранение файла",
                               settings->value("advanced/export_path", "").toString(), "Файл ядра Наследия (*.txt);;Все файлы (*)");
    if (fileName.isEmpty())
            return;

    settings->setValue("advanced/export_path", fileName.left(std::max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'))));
    settings->sync();

    qDebug() << "Saving export path to " << settings->value("advanced/export_path", "").toString();

    QMetaObject::invokeMethod(lotro_manager, "createCoreStatusFile", Qt::QueuedConnection,
                              Q_ARG(QString, fileName));
}

void ManageWidget::on_initButton_common_clicked()
{

    QMetaObject::invokeMethod(lotro_manager, "initialiseDatFile", Qt::QueuedConnection,
                              Q_ARG(QString, settings->value("advanced/dat_path", "").toString()));
}

void ManageWidget::on_deinitButton_common_clicked()
{
    QMetaObject::invokeMethod(lotro_manager, "deinitialiseDatFile", Qt::QueuedConnection);
}

void ManageWidget::on_activate_category_button_clicked()
{
    if (ui->activate_category_label->text().toLongLong() == 0) {
        QMessageBox::warning(this->parentWidget(), "Не указан ID категории!", "Укажите, пожалуйста, корректный (числовой) ID категории для активации!");
        return;
    }

    QMetaObject::invokeMethod(lotro_manager, "enableCategory", Qt::QueuedConnection,
                              Q_ARG(long long, ui->activate_category_label->text().toLongLong())
                              );

}

void ManageWidget::on_deactivate_category_button_clicked()
{
    if (ui->deactivate_category_label->text().toLongLong() == 0) {
        QMessageBox::warning(this->parentWidget(), "Не указан ID категории!", "Укажите, пожалуйста, корректный (числовой) ID категории для деактивации!");
        return;
    }

    QMetaObject::invokeMethod(lotro_manager, "disableCategory", Qt::QueuedConnection,
                              Q_ARG(long long, ui->deactivate_category_label->text().toLongLong())
                              );
}
