#include "Animatedsprite.h"
#include "Screen.h"

using namespace std;

//AnimatedSprite::AnimatedSprite(std::string filename)
//: Sprite( filename )
//{
//}
//
//AnimatedSprite::AnimatedSprite(std::string filename, int width, int height)
//: Sprite( filename, width, height )
//{
//}


AnimatedSprite::AnimatedSprite( std::string filename, List *spriteInfo )
:_time(0),_index(0),_loop(false),_totalTime(0)
{
	_filename = filename;

	while(!spriteInfo->empty()) {
		List *nextSprite = spriteInfo->firstList();

		if(nextSprite->firstString() == "sprite") {
			List *spriteParams = nextSprite->rest();
			SpriteTime spriteTime;

			while(!spriteParams->empty()) {
				if(spriteParams->firstList()->firstString() == "filename") {
					spriteTime.s = Sprite::loadSprite(spriteParams->firstList()->rest()->firstString());
				}
				else if(spriteParams->firstList()->firstString() == "time") {
					spriteTime.time = _totalTime;
					_totalTime += atoi( spriteParams->firstList()->rest()->firstString().c_str() );
				}
				spriteParams = spriteParams->rest();
			}

			_sprites.push_back(spriteTime);
		}
		else if(nextSprite->firstString() == "loop")
			_loop = true;

		spriteInfo = spriteInfo->rest();
	}

	if(_sprites.size() > 0) {
		_rect = _sprites[0].s->rect();
		for(size_t i = 1; i < _sprites.size(); i++) {
			if(_sprites[i].s->rect().h != _rect.h || _sprites[i].s->rect().w != _rect.w) {
				cerr << "Animated sprite not of consistent size: " << _sprites[i].s->filename()
					<< " conflicts in " << _filename << endl;
			}
		}
	}
	else {
		cerr << "Malformed animated sprites file: " << _filename << endl;
	}
}

AnimatedSprite::AnimatedSprite(AnimatedSprite *sprite)
:Sprite(sprite),_index(0),_time(0)
{
	_sprites = sprite->_sprites;
	_totalTime = sprite->_totalTime;
	_loop = sprite->_loop;
}

AnimatedSprite::~AnimatedSprite()
{
	clean();
}

void AnimatedSprite::clean()
{
	for(size_t i = 0; i < _createdSprites.size(); i++)
		delete _createdSprites[i];
	_createdSprites.clear();
}

void AnimatedSprite::update()
{
	if(_time > _totalTime)
		return;

	_time++;

	if(_loop)
		_time %= _totalTime;
	
	_index = _sprites.size() - 1;
	for(size_t i = 0; i < _sprites.size(); i++) {
		if(_time < _sprites[i].time) {
			_index = i-1;
			break;
		}
	}
}

void AnimatedSprite::draw(int x, int y, bool origin)
{
	xDirection tempDir = _sprites[_index].s->getDirection();
	
	_sprites[_index].s->setDirection(_direction);
	_sprites[_index].s->setRect(_rect);
	_sprites[_index].s->setBox(_box);
	_sprites[_index].s->draw(x,y, origin);
	
	_sprites[_index].s->setDirection(tempDir);
}

Sprite *AnimatedSprite::instance()
{
	Sprite *animatedSprite = new AnimatedSprite(this);
	_createdSprites.push_back(animatedSprite);
	return animatedSprite;
}