#include "fastfile_cod4_360.h"
#include "zonefile_cod4_360.h"

#include "utils.h"
#include "compression.h"
#include "statusbarmanager.h"

#include <QFile>
#include <QDebug>

FastFile_COD4_360::FastFile_COD4_360()
    : FastFile() {
    SetCompany(COMPANY_INFINITY_WARD);
    SetType(FILETYPE_FAST_FILE);
    SetSignage(SIGNAGE_UNSIGNED);
    SetMagic(0);
    SetVersion(0);
    SetPlatform("360");
    SetGame("COD4");
}

FastFile_COD4_360::FastFile_COD4_360(const QByteArray& aData)
    : FastFile_COD4_360() {

    if (!aData.isEmpty()) {
        Load(aData);
    }
}

FastFile_COD4_360::FastFile_COD4_360(const QString aFilePath)
    : FastFile_COD4_360() {

    if (!aFilePath.isEmpty()) {
        Load(aFilePath);
    }
}

FastFile_COD4_360::~FastFile_COD4_360() {

}

QByteArray FastFile_COD4_360::GetBinaryData() {
    return QByteArray();
}

bool FastFile_COD4_360::Load(const QString aFilePath) {
    StatusBarManager::instance().updateStatus("Loading COD5 Fast File w/path", 1000);

    if (aFilePath.isEmpty()) {
        return false;
    }

    // Check fastfile can be read
    QFile *file = new QFile(aFilePath);
    if (!file->open(QIODevice::ReadOnly)) {
        qDebug() << QString("Error: Failed to open FastFile: %1!").arg(aFilePath);
        return false;
    }

    // Decompress fastfile and close
    QString fastFileStem = aFilePath.split('/').last().replace(".ff", "");
    SetStem(fastFileStem);
    if (!Load(file->readAll())) {
        qDebug() << "Error: Failed to load fastfile: " << fastFileStem;
        return false;
    }

    file->close();

    // Open zone file after decompressing ff and writing
    return true;
}

bool FastFile_COD4_360::Load(const QByteArray aData) {
    StatusBarManager::instance().updateStatus("Loading COD5 Fast File w/data", 1000);
    QByteArray decompressedData;

    const QString header = aData.left(8);
    if (header == "IWffu100") {
        // For COD5, simply decompress from offset 12.
        decompressedData = Compression::DecompressZLIB(aData.mid(12));
    } else if (header == "IWff0100") {
        // Create a QDataStream on the input data.
        QDataStream fastFileStream(aData.mid(12));
        fastFileStream.setByteOrder(QDataStream::LittleEndian);

        QByteArray magic(8, Qt::Uninitialized);
        fastFileStream.readRawData(magic.data(), 8);
        if (magic != "IWffs100") {
            qDebug() << "Found invalid signed header: " << magic;
            return false;
        }
        fastFileStream.skipRawData(4);

        QByteArray rsaSigChecksum(32, Qt::Uninitialized);
        fastFileStream.readRawData(rsaSigChecksum.data(), 32);

        QByteArray rsaSig(256, Qt::Uninitialized);
        fastFileStream.readRawData(rsaSig.data(), 256);

        QByteArray fileName(32, Qt::Uninitialized);
        fastFileStream.readRawData(fileName.data(), 32);

        fastFileStream.skipRawData(4);

        QByteArray bigSigBlock(7856, Qt::Uninitialized);
        fastFileStream.readRawData(bigSigBlock.data(), 7856);

        QVector<QByteArray> sigBlocks = QVector<QByteArray>();
        QByteArray compressedData;

        for (int i = 0; i < (aData.size() / 202000) + 1; i++)
        {
            QByteArray newSigBlocks;
            for (int j = 0; j < 256; j++) {
                QByteArray newSigBlock(32, Qt::Uninitialized);
                fastFileStream.readRawData(newSigBlock.data(), 32);
                sigBlocks.append(newSigBlock);
            }
            newSigBlocks.append(newSigBlocks);
            for (int j = 0; j < 256; j++) {
                QByteArray compressedChunk(8192, Qt::Uninitialized);
                fastFileStream.readRawData(compressedChunk.data(), 8192);
                compressedData.append(compressedChunk);
            }
        }
        decompressedData = Compression::DecompressZLIB(compressedData);
    }
    Utils::ExportData(GetBaseStem() + ".zone", decompressedData);

    ZoneFile_COD4_360 zoneFile;
    zoneFile.SetStem(GetBaseStem() + ".zone");
    zoneFile.Load(decompressedData);
    SetZoneFile(std::make_shared<ZoneFile_COD4_360>(zoneFile));

    return true;
}
