#include "Animation.h"
#include "Log.h"

Animation::Animation(std::string path, int frameCount, std::chrono::milliseconds interval) : maxFrameCount(frameCount),
	frameInterval(interval)
{
	try {
		animationFrames.reserve(frameCount);
		spriteSheet = al_load_bitmap(path.c_str());
		if (spriteSheet == nullptr)
			Log::logError("Cannot Load the animation sprite: ", path);

		float bitMapWidth = al_get_bitmap_width(spriteSheet);
		float bitMapHeight = al_get_bitmap_height(spriteSheet);
		float eachFrameHeight = bitMapHeight / frameCount;

		centerX = bitMapWidth / 2;
		centerY = eachFrameHeight / 2;

		/* Start refactoring of the big Sprite sheet in horizontal cutting mode */
		try {
			for (int frameNo = 0; frameNo < frameCount; frameNo++)
			{
				float yOfThisFrame = frameNo * eachFrameHeight;
				animationFrames.emplace_back(al_create_sub_bitmap(spriteSheet, 0, yOfThisFrame,
					bitMapWidth, eachFrameHeight));

				if (animationFrames[frameNo] == nullptr)
					Log::logError("Error creating submap", path);
			}
		}
		catch (...) 
		{
			Log::logError("Cannot refactor the bitmap");
		}
	}
	catch (const std::exception& e)
	{
		Log::logError("Cannot construct animation");
		Log::logInfo(e.what());
	}
	catch (...)
	{
		Log::logError("Cannot construct an animation on path : ", path, " FrameCount = ", frameCount);
	}
}

Animation::~Animation()
{
}
