#include "asset_manager.h"
#include "zlog.h"
using namespace std;
namespace engineapi {
	void AssetManager::ClearAsset(Asset* asset)
	{
		auto it = mAssetMap.find(asset->mName);
		if (!asset->IsShared()) {
			delete asset;
		}
		if (it != mAssetMap.end()) {
			it->second.count--;
			if (it->second.count < 1) {
				delete it->second.asset;
				mAssetMap.erase(it);
			}
		}
	}
	string AssetManager::LoadTextFile(const string& path)
	{
		string text = "";
		ifstream file;
		file.exceptions(ifstream::failbit | ifstream::badbit);

		try
		{
			file.open(path);
			stringstream stream;
			stream << file.rdbuf();
			file.close();
			text = stream.str();
		}
		catch (ifstream::failure e)
		{
			zlog::info("Failed to load text file: {}", path);
		}

		return text;
	}
	vector<char> AssetManager::LoadBinaryFile(const string& path)
	{
		// ate:在文件末尾开始读取，从文件末尾开始读取的优点是我们可以使用读取位置来确定文件的大小并分配缓冲区
		ifstream file(path, std::ios::ate | std::ios::binary);
		if (!file.is_open()) {
			zlog::info("Failed to load binary file: {}", path);
			return vector<char>();
		}

		// 使用读取位置来确定文件的大小并分配缓冲区
		size_t fileSize = (size_t)file.tellg();
		vector<char> data(fileSize);

		// 返回文件开头，真正读取内容
		file.seekg(0);
		file.read(data.data(), fileSize);
		file.close();

		return data;
	}
	json AssetManager::LoadJsonFile(const string& path)
	{
		std::ifstream f(path);
		if (!f.is_open())
		{
			zlog::error("Load asset failed: {}", path);
			return NULL;
		}
		json data;
		try
		{
			data = json::parse(f);
		}
		catch (json::exception& e)
		{
			zlog::error("Asset format error: {}", path);
			string msg = e.what();
			zlog::error("Error detail: {}", msg);
		}
		return data;
	}
}
