
// ::Assets::Globals::Start::

u8 ASSET_PACK[] = 
{	
	#embed "../assets.sgp" 
};

static FileHeader File_Header = {0};

static AssetFile Texture_Assets[TEXTURE_ASSET_MAX];
static Asset 		 Texture_Asset_Lookup[TEXTURE_ASSET_MAX];

static AssetFile Shader_Assets[SHADER_ASSET_MAX];
static Asset		 Shader_Asset_Lookup[SHADER_ASSET_MAX];

// TODO(MA): Implement async asset handling
static u32			 Shader_Asset_Ref_Count[SHADER_ASSET_MAX];
static u32			 Texture_Asset_Ref_Count[TEXTURE_ASSET_MAX];

static b32 ASSET_HEADER_LOADED = false;


// ::Assets::Global::End::



// ::Assets::Init::Functions::Start::

static void apInit()
{
	MemCpy(&File_Header, ASSET_PACK, sizeof(FileHeader));

	Assert(File_Header.magic_num == CreateMagicValue('s', 't', 'e', 'g'), "Magic value is incorrect");

	MemCpy(Texture_Assets, &ASSET_PACK[File_Header.asset_offsets[TEXTURE_ASSET]], sizeof(AssetFile) * File_Header.asset_counts[TEXTURE_ASSET]);

	MemCpy(Shader_Assets, &ASSET_PACK[File_Header.asset_offsets[SHADER_ASSET]], sizeof(AssetFile) * File_Header.asset_counts[SHADER_ASSET]);

	ASSET_HEADER_LOADED = true;
}

// ::Assets::Init::Functions::End::



// ::Assets::Loading::Functions::Start::

static Asset apLoadTexture(TextureAsset asset_id)
{
	if (!ASSET_HEADER_LOADED)
	{
		apInit();
	}

	Assert(asset_id < i32(TEXTURE_ASSET_MAX), "LoadTextureAsset failure: asset_id is higher than TEXTURE_ASSET_MAX");

	Asset asset = Texture_Asset_Lookup[asset_id];

	if (asset.bytes == NULL)
	{
		AssetFile *asset_info = Texture_Assets + asset_id;
		u8 *img = FLMemAlloc(asset_info->len);
		MemCpy(img, &ASSET_PACK[asset_info->data_offset], asset_info->len);

		asset.bytes = img;
		asset.len = asset_info->len;

		Texture_Asset_Lookup[asset_id] = asset;
	}

	return asset;
}

static Asset apLoadShader(ShaderAsset asset_id)
{
	if (!ASSET_HEADER_LOADED)
	{
		apInit();
	}

	Assert(asset_id < SHADER_ASSET_MAX, "LoadShaderAsset failure: asset_id is higher than SHADER_ASSET_MAX");

	Asset asset = Shader_Asset_Lookup[asset_id];
	if (asset.bytes == NULL)
	{
		AssetFile *asset_info = Shader_Assets + asset_id;

		asset.bytes = FLMemAlloc(asset_info->len);
		MemCpy(asset.bytes, &ASSET_PACK[asset_info->data_offset], asset_info->len);
		asset.len = asset_info->len;
		Shader_Asset_Lookup[asset_id] = asset;
	}

	return asset;
}

static TextureAssetMeta apGetTextureMeta(TextureAsset asset_id)
{
	AssetFile *asset_file = Texture_Assets + asset_id;
	return asset_file->texture_meta;
}

static void apUnloadTexture(TextureAsset asset_id)
{
	Asset *asset = Texture_Asset_Lookup + asset_id;
	if (asset->bytes != NULL)
	{
		FLMemFree(asset->bytes);
		asset->bytes = NULL;
		asset->len = 0;
	}
}

static void apUnloadShader(ShaderAsset asset_id)
{
	Asset *asset = Shader_Asset_Lookup + asset_id;
	if (asset->bytes != NULL)
	{
		FLMemFree(asset->bytes);
		asset->bytes = NULL;
		asset->len = 0;
	}
}

// ::Assets::Loading::Functions::End::
