#include "browsewidget.h"
#include "ui_browsewidget.h"
#include "models/lotrodatmanager.h"
#include <QMessageBox>

BrowseWidget::BrowseWidget(LotroDatManager* mgr, QSettings* settings, QWidget *parent) :
    QWidget(parent), lotro_manager(mgr), settings(settings),
    ui(new Ui::BrowseWidget)
{
    ui->setupUi(this);
    //void localeFileInfoReceived(QString);
    connect(lotro_manager, &LotroDatManager::localeFileContentsReceived, this, &BrowseWidget::onLotroLocaleFileContentsReceived);
    connect(lotro_manager, &LotroDatManager::localeFileInfoReceived, this, &BrowseWidget::onLotroLocaleFileInfoReceived);
    resize(parent->size());
}

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

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


    QMetaObject::invokeMethod(lotro_manager, "getLocaleFileContents", Qt::QueuedConnection,
                              Q_ARG(long long, ui->file_id_common->text().toLongLong()),
                              Q_ARG(int, LOTRO_DAT::DatLocaleManager::PATCHED)
                              );


    QMetaObject::invokeMethod(lotro_manager, "getLocaleFileContents", Qt::QueuedConnection,
                              Q_ARG(long long, ui->file_id_common->text().toLongLong()),
                              Q_ARG(int, LOTRO_DAT::DatLocaleManager::ORIGINAL)
                              );
}

void BrowseWidget::onLotroLocaleFileContentsReceived(int locale, LOTRO_DAT::SubfileData data)
{
    //void localeFileContentsReceived(int, LOTRO_DAT::SubfileData); // extention, contents
    //void localeFileInfoReceived(QString);

    QLabel* target_contents;
    QLineEdit* target_args;
    if (locale == LOTRO_DAT::DatLocaleManager::PATCHED) {
        target_args = ui->patched_args_common;
        target_contents = ui->patched_content_common;
    } else {
        target_args = ui->original_args_common;
        target_contents = ui->original_content_common;
    }

    if (ui->fragment_id_common->text().toLongLong() == 0) {
        target_contents->setText(QString::fromStdU16String(data.text_data));
        target_args->clear();
        return;
    }

    long long fragment_id = ui->fragment_id_common->text().toLongLong();

    unsigned beginning = data.text_data.find(QString::number(fragment_id).toStdU16String(), 0);
    if (beginning == std::u16string::npos) {
        QMessageBox::warning(this->parentWidget(), "Фрагмент не найден!", "Не удалось найти в файле фрагмент с заданным ID!");
        return;
    }

    unsigned ending = data.text_data.find(QString("|||").toStdU16String(), beginning);

    unsigned size = std::u16string::npos;

    if (ending != std::u16string::npos)
        size = ending - beginning;

    std::u16string str = data.text_data.substr(beginning, size);

    QStringList splitted_fragment = QString::fromStdU16String(str).split(":::");
    if (splitted_fragment.size() != 3) {
        QMessageBox::warning(this->parentWidget(), "Ошибка импорта!", QString("Получены некорректные данные фрагмента! Будет выведен весь файл!"));
        target_contents->setText(QString::fromStdU16String(str));
        target_args->clear();
        return;
    }

    target_args->setText(splitted_fragment.at(1));
    target_contents->setText(splitted_fragment.at(2));
    return;
}

void BrowseWidget::onLotroLocaleFileInfoReceived(int locale, QString info)
{
    QLabel* target_contents;
    QLineEdit* target_args;
    if (locale == LOTRO_DAT::DatLocaleManager::PATCHED) {
        target_args = ui->patched_args_common;
        target_contents = ui->patched_content_common;
    } else {
        target_args = ui->original_args_common;
        target_contents = ui->original_content_common;
    }

    target_args->clear();
    target_contents->setText(info);
}

void BrowseWidget::on_getFileInfoButton_common_clicked()
{
    QMetaObject::invokeMethod(lotro_manager, "getLocaleFileInfo", Qt::QueuedConnection,
                              Q_ARG(long long, ui->file_id_common->text().toLongLong()),
                              Q_ARG(int, LOTRO_DAT::DatLocaleManager::ORIGINAL)
                              );

    QMetaObject::invokeMethod(lotro_manager, "getLocaleFileInfo", Qt::QueuedConnection,
                              Q_ARG(long long, ui->file_id_common->text().toLongLong()),
                              Q_ARG(int, LOTRO_DAT::DatLocaleManager::PATCHED)
                              );
}
