#include "Animation.hpp"
#include "AnimatedSprite.hpp"
#include "Echo.hpp"

AnimatedSprite::AnimatedSprite()
{
	_current = nullptr;
	_jumping = false;
	armored = true;
}

AnimatedSprite::~AnimatedSprite()
{
	_current = nullptr;
	_anim.clear();
}

void AnimatedSprite::addAnimation(std::string armored, std::string filename, unsigned duration, std::string name, bool loop)
{
	_anim[name].tex1.loadFromFile(armored);
	_anim[name].tex2.loadFromFile(filename);
	_anim[name].duration = duration;
	_anim[name].name = name;
	_anim[name].loop = loop;
	Echo(LOAD, "Registered animation ", name, " from ", filename, '.');
}

void AnimatedSprite::setAnimation(std::string name, bool armored)
{
	/// If it's already set, abort.
	if(_current == &_anim[name]) {
		return;
	}
	_current = &_anim[name];
	if(_current == nullptr) {
		Echo(ERROR, "Attempted to use an inexisting animation ", name, '.');
	}
	if(armored)
	_current->tex = _current->tex1;
	else
	_current->tex = _current->tex2;
	setTexture(_current->tex);
	setTextureRect(IntRect(0, 0,
						_current->tex.getSize().x / _current->count, _current->tex.getSize().y / _current->count));
	_anclock.restart();
}

void AnimatedSprite::animate()
{
	if(_current == nullptr) {
		return;
	}
	const unsigned duration = _current->duration;
	if(duration == 0) {
		setAnimation("idle", armored);
	}

 	unsigned elapsed = _anclock.getElapsedTime().asMilliseconds() % duration;
	unsigned frame = (elapsed * _current->count) / duration;
	setTextureRect(IntRect(_current->tex.getSize().x * frame / _current->count, 0,
						_current->tex.getSize().x / _current->count, _current->tex.getSize().y));
}
