#include "CutScene.h"
#include "Parser.h"
#include "Command.h"
#include "CommandManager.h"

using namespace std;

CutScene::CutScene(List* info, int x, int y)
:Object(info,x,y),_active(true),_keyTimer(0)
{

	_type = CUTSCENE;
	_solid = false;
	load(info);
}

CutScene::~CutScene()
{
	while(!_scene.empty())
	{
		delete _scene.front();
		_scene.pop();
	}
}

Object *CutScene::copy()
{
	CutScene *copy = new CutScene(*this);
	copy->_scene.c.clear();
	for(size_t i = 0; i < _scene.c.size(); i++)
		copy->_scene.c.push_back(new List(_scene.c[i]));

	return copy;
}

void CutScene::load(List *info)
{
	while(!info->empty()) {
		List *current = info->firstList();

		if(current->firstString() == "scene"){
			_scene.push(new List(current->rest()->rest()));
			_waitTime.push(current->rest()->firstInt());
		}
			

		info = info->rest();
	}
	_keyTimer = _waitTime.front()+1;
}

void CutScene::collide(Object *o)
{
	if(o->getType() == PLAYER && _active)
		activate();
}

void CutScene::activate()
{
	CommandManager::instance()->flush();
	runScene();
	_keyTimer = 0;
	_active = false;
}

void CutScene::control()
{
	Uint8 *keystates = SDL_GetKeyState( NULL );

	if(keystates[SDLK_SPACE] && _keyTimer > _waitTime.front()) {
		_keyTimer = 0;
		runScene();
	}
}

void CutScene::runScene()
{
	if(_scene.empty()) {
		cerr << "Control still on " << _id << " after scene is over." << endl;
		return;
	}

	/*
	queue<Command*> commands = _scene.front();
	_scene.pop();

	while(!commands.empty()) {
		commands.front()->execute();
		commands.pop();
	}
	*/

	List *commands = _scene.front();

	//int waitTime = 0;
	while(!commands->empty()) {
		Command *command = Command::loadCommand(commands->firstList());
		command->execute();
		commands = commands->rest();
	}

	delete _scene.front();
	_scene.pop();
	_waitTime.pop();
}