#include "fastfile_cod7_pc.h"
#include "zonefile_cod7_pc.h"

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

#include <QFile>
#include <QDebug>

FastFile_COD7_PC::FastFile_COD7_PC()
    : FastFile() {
    SetCompany(COMPANY_INFINITY_WARD);
    SetType(FILETYPE_FAST_FILE);
    SetSignage(SIGNAGE_UNSIGNED);
    SetMagic(0);
    SetVersion(0);
    SetGame("COD7");
    SetPlatform("PC");
}

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

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

FastFile_COD7_PC::FastFile_COD7_PC(const QString aFilePath)
    : FastFile_COD7_PC() {

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

FastFile_COD7_PC::~FastFile_COD7_PC() {

}

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

bool FastFile_COD7_PC::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_COD7_PC::Load(const QByteArray aData) {
    QByteArray decompressedData;

    // Create a XDataStream on the input data.
    XDataStream fastFileStream(aData);
    fastFileStream.setByteOrder(XDataStream::LittleEndian);

    // Parse header values.
    SetCompany(pParseFFCompany(&fastFileStream));
    SetType(pParseFFFileType(&fastFileStream));
    SetSignage(pParseFFSignage(&fastFileStream));
    SetMagic(pParseFFMagic(&fastFileStream));
    quint32 version = pParseFFVersion(&fastFileStream);
    SetVersion(version);
    SetPlatform("360");
    SetGame("COD7");

    // Assume the first 12 bytes are a header; the rest is zlib-compressed zone data.
    const QByteArray compressedData = aData.mid(12);
    decompressedData = Compression::DecompressZLIB(compressedData);

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

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

    return true;
}
