#include "ShowOneSprite.h"

using namespace std;

ShowOneSprite::ShowOneSprite( std::string filename, List *spriteInfo )
:_index(0)
{
	_filename = filename;

	bool bBox = false;;

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

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

			while(!spriteParams->empty()) {
				if(spriteParams->firstList()->firstString() == "filename") {
					sprite = Sprite::loadSprite(spriteParams->firstList()->rest()->firstString());
				}
				else if(spriteParams->firstList()->firstString() == "origin" && sprite) {
					List *boxInfo = spriteParams->firstList()->rest();

					SDL_Rect rect = sprite->rect();

					rect.x = boxInfo->firstInt();
					boxInfo = boxInfo->rest();
					rect.y = boxInfo->firstInt();

					sprite->setRect(rect);
					bBox = true;
				}
				spriteParams = spriteParams->rest();
			}

			_sprites.push_back(sprite);
		}
		else if(nextSprite->firstString() == "size") {
			_box.w = nextSprite->rest()->firstInt();
			_box.h = nextSprite->rest()->rest()->firstInt();
		}

		spriteInfo = spriteInfo->rest();
	}

	
	/*
	if(!bBox) {
		_rect = _sprites[0]->rect();
		for(size_t i = 1; i < _sprites.size(); i++) {
			if(_sprites[i]->rect().h != _rect.h || _sprites[i]->rect().w != _rect.w) {
				cerr << "Showone sprite not of consistent size: " << _sprites[i]->filename()
					<< " conflicts in " << _filename << endl;
			}
		}
		_box = _rect;
	}
	*/
}

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

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

	_createdSprites.clear();
}

ShowOneSprite::ShowOneSprite(ShowOneSprite *sprite)
:Sprite(sprite),_index(0)
{
	_sprites = sprite->_sprites;
}

void ShowOneSprite::draw(int x, int y, bool origin)
{
	xDirection tempDir = _sprites[_index]->getDirection();
	SDL_Rect tempBox = _sprites[ _index ]->box();
	_sprites[_index]->setDirection(_direction);
	_sprites[_index]->setBox( _box );
	_sprites[_index]->draw(x, y, origin);
	_sprites[_index]->setDirection(tempDir);
	_sprites[_index]->setBox( tempBox );
}

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

void ShowOneSprite::reset()
{
	for(size_t i = 0; i < _sprites.size(); i++)
		_sprites[i]->reset();
}

void ShowOneSprite::reset(int index)
{
	_sprites[index]->reset();
}