#include "animationEffect.h"
#include <algorithm>
using namespace std;


bool sortOperator( AnimationFrame frame1, AnimationFrame frame2)
{
	return (frame1.time < frame2.time);
}

AnimationManager::~AnimationManager()
{
	for ( std::map< std::string, vector< AnimationFrame >*  >::iterator it= this->animations.begin(); it!= this->animations.end(); ++it )
	{
		delete it->second;
	}

	this->animations.clear();
}

bool AnimationManager::insertAnimation( const std::string &name, const std::vector< AnimationFrame >& animation )
{
	std::map< std::string, vector< AnimationFrame >*  >::iterator it = this->animations.find( name );

	if ( it != this->animations.end() )
	{
		// could not be inserted, already in database
		return false;
	}
	else
	{
		std::vector< AnimationFrame > *newAnim = new std::vector< AnimationFrame >();
		*newAnim = animation;
		
		//sort ascending according the frame time
		sort( newAnim->begin(), newAnim->end(), sortOperator );

		this->animations.insert( make_pair( name, newAnim )); 
	}

	// successfully inserted
	return true;
}

bool AnimationManager::removeAnimation( const std::string &name )
{
	std::map< std::string, vector< AnimationFrame >*  >::iterator it = this->animations.find( name );

	if ( it == this->animations.end() )
	{
		// could not be deleted, not in database
		return false;
	}
	else
	{
		delete it->second;
		this->animations.erase( it );
	}

	// successfully deleted
	return true;
}

const std::vector< AnimationFrame >* AnimationManager::getAnimation( const std::string &name )
{
	std::map< std::string, vector< AnimationFrame >*  >::iterator it = this->animations.find( name );

	if ( it == this->animations.end() )
	{
		// not in database
		return NULL;
	}
	
	return it->second;
}

void AnimationEffect::simulate( float dt )
{
	this->animationTime += dt;

	// switch to next frame if animation time is greater than frame time
	if ( this->animPtr.size() > this->lastFrameIdx+1 )
	{
		if ( this->animationTime >= this->animPtr[this->lastFrameIdx +1 ].time  )
		{
			//use next frame
			++this->lastFrameIdx;
		}
		else
		{
			//use old frame
		}
	}
}

void AnimationEffect::render( Render & render )
{
	Billboard billboard;
	billboard.position = this->pos;
	billboard.color.col.Set( 1,1,1);
	billboard.color.w= 1;
	billboard.size[0] = this->size[0];
	billboard.size[1] = this->size[1];
	
	billboard.texID = this->animPtr[ this->lastFrameIdx ].textureId;
	if ( billboard.texID == 0 ) return;
	render.renderBillboard( billboard );
}