#include "AndroidAssetManager.h"
#include "Log.h"

#include <game-activity/native_app_glue/android_native_app_glue.h>

AndroidAssetManager::AndroidAssetManager() : AssetManager(), m_asset_mgr(nullptr){};
AndroidAssetManager::~AndroidAssetManager() {}

void AndroidAssetManager::create(AAssetManager* android_asset_manager)
{
    AndroidAssetManager* m = new AndroidAssetManager;
    m->m_asset_mgr = android_asset_manager;
    AssetManager::ptr = m;
}

bool AndroidAssetManager::loadFile(const char* path, FileBuffer* p_file_buffer)
{
    AAsset* asset = AAssetManager_open(m_asset_mgr, path, AASSET_MODE_BUFFER);
    if (!asset) {
        ALOGE("Failed to open asset %s", path);
        return false;
    }
    const void* buffer = AAsset_getBuffer(asset);
    if (!buffer) {
        ALOGE("Failed to retrieve contents of asset %s", path);
        return false;
    }
    auto length = static_cast<size_t>(AAsset_getLength64(asset));
    p_file_buffer->data = buffer, p_file_buffer->size = length;
    p_file_buffer->internal = asset;
    return true;
}

void AndroidAssetManager::releaseFileBuffer(FileBuffer& fb)
{
    AAsset_close(reinterpret_cast<AAsset*>(fb.internal));
    fb.internal = nullptr;
    fb.data = nullptr;
    fb.size = 0;
}