#include "Animation.hpp"
#include "AnimatedSprite.hpp"
#include "Log.hpp"

AnimatedSprite::AnimatedSprite():
m_current_anim(nullptr),
m_speed(1.f) {
	
}

AnimatedSprite::~AnimatedSprite() {
	
}

void AnimatedSprite::addAnimation(std::string filename, unsigned duration, std::string name, bool loop, unsigned width) {
	m_anim[name].texture.loadFromFile(filename);
	m_anim[name].duration = duration;
	m_anim[name].name = name;
	m_anim[name].loop = loop;
	m_anim[name].count = m_anim[name].texture.getSize().x / width;
	Log(LOAD, "Registered animation ", name, " from ", filename, '.');
}

void AnimatedSprite::setAnimation(std::string name) {
	/// If it's already set, abort.
	if(m_current_anim == &m_anim[name]) {
		return;
	}
	m_current_anim = &m_anim[name];
	if(!m_current_anim) {
		Log(ERROR, "Attempted to use an inexisting animation ", name, '.');
	}
	setTexture(m_current_anim->texture);
	setTextureRect(sf::IntRect(
		0, 
		0, 
		m_current_anim->texture.getSize().x / m_current_anim->count, 
		m_current_anim->texture.getSize().y / m_current_anim->count)
	);
	m_clock.restart();
}

void AnimatedSprite::setAnimationSpeed(float speed) {
	m_speed = speed;
}

void AnimatedSprite::animate() {
	if(m_current_anim 
	&& m_current_anim->duration > 0 
	&&(m_current_anim->loop || m_clock.getElapsedTime().asMilliseconds() < m_current_anim->duration / m_speed)) {
		unsigned elapsed = m_clock.getElapsedTime().asMilliseconds() % int(m_current_anim->duration / m_speed);
		unsigned frame = (elapsed * m_current_anim->count) / int(m_current_anim->duration / m_speed);
		
		setTextureRect(sf::IntRect(
			m_current_anim->texture.getSize().x * frame / m_current_anim->count, 
			0,
			m_current_anim->texture.getSize().x / m_current_anim->count, 
			m_current_anim->texture.getSize().y)
		);
	}
}
