#include "loader.h"

#include <QDebug>
#include <QFile>
#include <QJsonDocument>

class LoaderPrivate
{
public:
    LoaderPrivate(Loader *parent) : q_ptr(parent) {}

    Loader *q_ptr;
    Q_DECLARE_PUBLIC(Loader)
};

Loader::Loader(QObject *parent) :
    QObject(parent), dd_ptr(new LoaderPrivate(this))
{

}

Loader::~Loader()
{

}

QJsonObject Loader::loadExtentData(const QString &file)
{
    QFile externFile(file);
    if (!externFile.open(QIODevice::ReadOnly)) {
        qCritical() << "open" << file << "failed";
        return QJsonObject();
    }

    if (externFile.size() < 128) {
        qCritical() << file << "to small";
        return QJsonObject();
    }

    quint32 magicNumber = 0;
    externFile.seek(externFile.size() - 4);
    externFile.read(reinterpret_cast<char *>(&magicNumber), sizeof(magicNumber));
    qDebug() << "magicNumber" << magicNumber;
    if (0x1CE4E271 != magicNumber) {
        return QJsonObject();
    }

    externFile.seek(externFile.size() - 8);
    quint32 externSize = 0;
    externFile.read(reinterpret_cast<char *>(&externSize), sizeof(externSize));
    qDebug() << "externSize" << externSize;

    externFile.seek(externFile.size() - 8 - externSize);
    auto jsonData = externFile.read(externSize);

    return QJsonDocument::fromJson(jsonData).object();
}

void Loader::packageExtentData(const QString &srcPath, const QString &jsonPath)
{
    QFile jsonFile(jsonPath);
    jsonFile.open(QIODevice::ReadOnly);
    auto jsonData = jsonFile.readAll();
    jsonFile.close();

    QFile srcFile(srcPath);
    srcFile.open(QIODevice::Append);
    srcFile.write(jsonData);

    quint32 externSize = static_cast<quint32>(jsonData.size());
    srcFile.write(reinterpret_cast<char *>(&externSize), sizeof(externSize));

    quint32 magicNumber = 0x1CE4E271;
    qDebug() << "magicNumber" << magicNumber;
    srcFile.write(reinterpret_cast<char *>(&magicNumber), sizeof(magicNumber));

    srcFile.close();
}


