
#include "ActionMove.h"
#include "Unit.h"
#include "GroundMap.h"

#include "MemoryManager/debugNew.h"

using namespace RenderSystem;

ActionMove::ActionMove(Unit * u,unitEnumeration::UnitState state, Point2D p) : UnitAction(u,state){
	unit = u;
	destination = p;
}


ActionMove::~ActionMove(void){
}

void ActionMove::execute()
{
	Point2D position = unit->getPosition();
	int tmpX = (int)(destination.getX()+0.5f)-(int)(position.getX()+0.5f);
	int tmpY = (int)(destination.getY()+0.5f)-(int)(position.getY()+0.5f);
	if (abs(tmpX)>=2 || abs(tmpY)>=2){
		dispose();
		return;
	}
	/**
	 * on restaure l'etat de l'unité
	 */
	unit->setState(this->unitState);
	unit->allowDust(true);
	float x = destination.getX()-position.getX();
	float y = destination.getY()-position.getY();
	float distance = sqrt( x*x + y*y  );
	float arriveX;
 	float arriveY;
	float speed = unit->getSpeed();
	
	// gestion de l'animation
	if(unit->getCurrentAnimation() != RenderableEntity::WALK ) {
		unit->setAnimation(RenderableEntity::WALK, unit->isMounted());
	}
	
	if (!(position == destination)){
		unit->setOrientation(position.getAngle(destination));
	}

	if(distance > unit->getRadius()) {
		// on ne pourra pas atteindre le point mais on s'en rapproche
		arriveX = (x / distance) * speed;	
		arriveY = (y / distance) * speed ;
		unit->pushAction(this);
		unit->setPosition(Point2D(position.getX() + arriveX,position.getY() + arriveY));
	} else {
		// l'action n'est plus utilisée : on la supprime
		dispose();
	}
}
