#include "fastfile_cod6_360.h"
#include "zonefile_cod6_360.h"

#include "compression.h"
#include "encryption.h"
#include "utils.h"

#include <QFile>
#include <QDebug>

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

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

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

FastFile_COD6_360::FastFile_COD6_360(const QString aFilePath)
    : FastFile_COD6_360() {

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

FastFile_COD6_360::~FastFile_COD6_360() {

}

QByteArray FastFile_COD6_360::GetBinaryData() const {
    return QByteArray();
}

bool FastFile_COD6_360::Load(const QString aFilePath) {
    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
    const QString fastFileStem = aFilePath.section("/", -1, -1);
    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_COD6_360::Load(const QByteArray aData) {
    const qint64 zlibOffset = Compression::FindZlibOffset(aData);
    if (zlibOffset == -1)
    {
        qWarning() << "Z-Lib stream not found";
        return false;
    }
    QByteArray compressed = aData.mid(zlibOffset);

    QByteArray decompressedData = Compression::DecompressZLIB(compressed);

    if (decompressedData.isEmpty() || decompressedData.size() < 1024)
    {
        QByteArray stripped = Compression::StripHashBlocks(compressed);
        QByteArray retry = Compression::DecompressZLIB(stripped);
        if (!retry.isEmpty())
            decompressedData.swap(retry);
    }

    if (decompressedData.isEmpty())
    {
        qWarning() << "Unable to decompress fast-file";
        return false;
    }

    Utils::ExportData(GetBaseStem() + ".zone", decompressedData);

    ZoneFile_COD6_360* zoneFile = new ZoneFile_COD6_360();
    zoneFile->SetStem(GetBaseStem() + ".zone");
    if (!zoneFile->Load(decompressedData)) {
        qWarning() << "Failed to load ZoneFile!";
        return false;
    }
    SetZoneFile(zoneFile);

    return true;
}
