#include "EventPoint.h"
#include "CommandManager.h"
#include "List.h"
#include "Parser.h"
#include "Sprite.h"
#include <iostream>

using namespace std;

EventPoint::EventPoint(List* info, int x, int y)
:Object(info,x,y),_active(true),_collideEvent(false),_hasSprite(false),_collideList(NULL)
{
	_collidable = true;
	_solid = false;
	_type = EVENTPOINT;

	//FIXME make me load this in
	//_box.h = 32;
	//_box.w = 32;

	load(info);
}

EventPoint::~EventPoint()
{
	delete _collideList;
}

Object *EventPoint::copy()
{
	EventPoint* copy = new EventPoint(*this);
	copy->_collideList = new List(_collideList);
	return copy;
}

void EventPoint::load(List *info, bool fromConstructor)
{
	if(!fromConstructor)
		Object::load(info,fromConstructor);

	while(!info->empty()) {
		List *current = info->firstList();

		if(current->firstString() == "collideScript") {
			if(current->rest()->first()->atomic()) {
				string collideFile = current->rest()->firstString();
				_collideList = Parser::parse(collideFile);
			}
			else {
				_collideList = new List(current->rest()->firstList());
			}
			_collideEvent = true;
		}
		else if(current->firstString() == "sprite") {
			_sprite = Sprite::loadSprite(current->rest()->firstString());
			_hasSprite = true;
			_box.h = _sprite->height();
			_box.w = _sprite->width();
		}
		else if(current->firstString() == "replace") {
			findAndReplace(current->rest()->firstString(), current->rest()->rest()->firstString());
		}

		info = info->rest();
	}

}

void EventPoint::collide(Object *o)
{
 	if(o->getType() == PLAYER && _active && _collideEvent) {
		CommandManager::instance()->startPlaying(_collideList);
		_active = false;
	}
}

void EventPoint::findAndReplace(std::string find, std::string replace)
{
	if(_collideEvent) {
		_collideList->findAndReplace(find,replace);
	}
}

void EventPoint::draw()
{
	if(_hasSprite && _active)
		_sprite->draw(_box.x,_box.y);
}