#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "compression.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(ui->plainTextEdit_Input, &QPlainTextEdit::textChanged, this, &MainWindow::InputChanged);
}

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

void MainWindow::InputChanged()
{
    QString input = ui->plainTextEdit_Input->toPlainText();
    if (input.isEmpty()) {
        qDebug() << "Input data was empty!";
        return;
    }

    QByteArray inputData = QByteArray::fromHex(input.remove(' ').toUtf8());
    if (inputData.isEmpty()) {
        qDebug() << "Failed to parse valid HEX data!";
        return;
    }

    bool flagOk;
    int flag = QString("0x%1").arg(ui->spinBox_Flags->value()).toInt(&flagOk, 16);
    if (!flagOk)
    {
        qDebug() << "Failed to parse flag!";
        return;
    }

    bool windowSizeOk;
    int windowSize = QString("0x%1").arg(ui->spinBox_WindowSize->value()).toInt(&windowSizeOk, 16);
    if (!windowSizeOk)
    {
        qDebug() << "Failed to parse window size!";
        return;
    }

    bool partSizeOk;
    int partitionSize = QString("0x%1").arg(ui->spinBox_PartitionSize->value()).toInt(&partSizeOk, 16);
    if (!partSizeOk)
    {
        qDebug() << "Failed to parse partition size!";
        return;
    }

    try {
        QByteArray output = Compression::DecompressXMem(inputData, flag, windowSize, partitionSize);
        ui->plainTextEdit_Output->setPlainText(output.toHex(' ').toUpper());
    } catch (const std::exception &e) {
        ui->plainTextEdit_Output->setPlainText(QString("Decompression failed: %1").arg(e.what()));
    } catch (...) {
        ui->plainTextEdit_Output->setPlainText("Decompression failed: Unknown error");
    }
}
