#include "Command.h"
#include "Person.h"
#include "List.h"
#include "Level.h"
#include "Sprite.h"

#include <string>
using namespace std;

const string AimCommand::_id = "aim";


AimCommand::AimCommand(Person *person, yDirection yDir)
:_person(person->id()),_yDir(yDir),_target(NULL)
{
	//cerr << "AimCommand" << endl;
}

//With the target
AimCommand::AimCommand(Person *person, Object *target)
:_person(person->id()),_target(target),_yDir(MIDDLE)
{
	if(_target == NULL)
		_target = (Object *)Level::instance()->getPlayer();

	//cerr << "AimCommand: aiming at " << _target->id() << endl;
}

AimCommand::AimCommand(List *command)
{
	command = command->rest();
	_person = command->firstString();
	command = command->rest()->firstList();
	if(command->firstString() == "direction")
	{
		_target = NULL;
		_yDir = (yDirection)command->rest()->firstInt();
	}
	else if(command->firstString() == "object")
	{
		_target = Level::instance()->getObject(command->rest()->firstString());
		_yDir = MIDDLE;
	}
}

void AimCommand::execute()
{
	Person *person = (Person *)Level::instance()->getObject(_person);
	if(person == NULL)
		return;

	if(_target != NULL)
	{
		SDL_Rect temp = person->getBox();

		if(glfuncs::intersectX(temp, _target->getBox()))
		{
			int dist = _target->getBox().y - temp.y;

			//cerr << "yDistance: "<< dist << endl;
			//cerr << "height" << _target->getBox().h << endl;

			if(abs(dist) < _target->getBox().h)
				_yDir = MIDDLE;
			else
				_yDir = (yDirection)(dist/abs(dist));
		}
	}
	
	person ->aim(_yDir);
}
std::string AimCommand::getString()
{
	List *command = new List();
	command->snoc(new Atom(_id));
	command->snoc(new Atom(_person));
	if(_target == NULL)
	{
		List *subList = new List();
		subList->snoc(new Atom("direction"));
		subList->snoc(new Atom(_yDir));
		command->snoc(subList);
	}
	else
	{
		List *subList = new List();
		subList->snoc(new Atom("object"));
		subList->snoc(new Atom(_target->id()));
		command->snoc(subList);
	}
	string commandString = command->getString();
	delete command;

	return commandString;
}

	
