#include "Command.h"
#include "Person.h"
#include "List.h"
#include "Level.h"
#include "Player.h"
#include <cmath>

#include <iostream>

using namespace std;

const std::string RunFromPlayerInRangeCommand::_id = "runFromPlayerInRange";

RunFromPlayerInRangeCommand::RunFromPlayerInRangeCommand(Person *person, int range)
:_person(person),_range(range)
{
}

RunFromPlayerInRangeCommand::RunFromPlayerInRangeCommand(List *command)
{
	command = command->rest();
	_person = (Person *)Level::instance()->getObject(command->firstString());
	command = command->rest();
	_range = command->firstInt();
}
void RunFromPlayerInRangeCommand::execute()
{
	Player* player = Level::instance()->getPlayer();
	int dist = player->getBox().x-_person->getBox().x;
	xDirection dir;
	//This is the only change from FollowPlayerInRangeCommand
	if (dist > 0)
		dir = LEFT;
	else
		dir = RIGHT;

	dist = sqrt(pow((player->getBox().x-_person->getBox().x),2)+
					pow((player->getBox().y-_person->getBox().y),2));
	if(dist <= _range)
		MoveCommand(_person,dir).execute();
	else
		TurnCommand(_person,dir).execute();
}
std::string RunFromPlayerInRangeCommand::getString()
{
	List *command = new List();
	command->snoc(new Atom(_id));
	command->snoc(new Atom(_person->id()));
	command->snoc(new Atom(_range));

	string commandString = command->getString();
	delete command;

	return commandString;
}