#include "AssetLoader.h"
#include "Log.h"

std::string AssetLoader::getPath(std::string& dataLine)
{
	try {
		std::string path = dataLine.substr(dataLine.find("path="));
		std::string realPath = path.substr(5);
		return realPath.substr(0, realPath.find_first_of("\t\n"));
	}
	catch (const std::exception& e)
	{
		Log::logError("Cannot recover path from data line : ", dataLine);
		Log::logInfo(e.what());
		return std::string("error");
	}
}

int AssetLoader::getFrameCount(std::string& dataLine)
{
	try {
		std::string frame = dataLine.substr(dataLine.find("frame="));
		std::string frameCount = frame.substr(6);
		frameCount = frameCount.substr(0, frameCount.find_first_of("\t\n"));
		return std::stoi(frameCount);
	}
	catch (const std::exception& e)
	{
		Log::logError("Cannot recover frame count from data line : ", dataLine);
		Log::logInfo(e.what());
		return 1;
	}
}

std::chrono::milliseconds AssetLoader::getInterval(std::string& dataLine)
{
	try {
		std::string frameInterval = dataLine.substr(dataLine.find("interval="));
		std::string interval = frameInterval.substr(9);
		interval = interval.substr(0, interval.find_first_of("\t\n"));
		return std::chrono::milliseconds(std::stoi(interval));
	}
	catch (const std::exception& e)
	{
		Log::logError("Cannot recover interval time from data line : ", dataLine);
		Log::logInfo(e.what());
		return std::chrono::milliseconds(0);
	}
}

AnimationPack* AssetLoader::loadAsset(std::string folderName)
{
	std::ifstream configFile;
	std::string fileSource = "Assets\\" + folderName + "\\" + folderName + ".info";
	std::string assetSource = "Assets\\" + folderName + "\\";
	try {
		
		/* Open The configuration file */
		configFile.open(fileSource, std::ios::in);
		if (!configFile.is_open())
		{
			Log::logError("Cannot open the Asset File :", fileSource);
			return nullptr;
		}

		/* read all the file content into a string vector */
		std::vector<std::string>dataChunks;
		while (!configFile.eof())
		{
			std::string data;
			std::getline(configFile, data);
			dataChunks.push_back(data);
		}
		configFile.close();

		AnimationPack* animationPack = new AnimationPack((int)dataChunks.size());
	
		/*		parse the string for frame count and path
				load all the animation sprite and place it in the animation queue	*/
		for (int i = 0; i < dataChunks.size(); i++)
		{
			auto assetPath = assetSource + getPath(dataChunks[i]);
			auto frameCount = getFrameCount(dataChunks[i]);
			auto interval = getInterval(dataChunks[i]);
			if (assetPath != "error")
				animationPack->addAnimation(assetPath, frameCount, interval);
		}
		Log::logInfo("Asset Loading Completed: ", folderName);
		return animationPack;		
	}
	catch (const std::exception& e)
	{
		Log::logError("AssetLoader() exception caught : ", folderName);
		Log::logInfo(e.what());
		return nullptr;
	}
}
