#include "component_control_move.h"

/* DEPENDENCIES: Physics */

static void _direction_update(ComponentControlMove* self, ECS* ecs);

/* Updates current direction. */
static void
_direction_update(ComponentControlMove* self, ECS* ecs)
{
	if
	(
		input_held(&ecs->game->input, INPUT_LEFT) &&
		input_held(&ecs->game->input, INPUT_UP)
	)
		self->direction = DIRECTION_NORTH_WEST;
	else if
	(
		input_held(&ecs->game->input, INPUT_RIGHT) &&
		input_held(&ecs->game->input, INPUT_UP)
	)
		self->direction = DIRECTION_NORTH_EAST;
	else if
	(
		input_held(&ecs->game->input, INPUT_DOWN) &&
		input_held(&ecs->game->input, INPUT_LEFT)
	)
		self->direction = DIRECTION_SOUTH_WEST;
	else if 
	(
		input_held(&ecs->game->input, INPUT_DOWN) &&
		input_held(&ecs->game->input, INPUT_RIGHT)
	)
		self->direction = DIRECTION_SOUTH_EAST;
	else if (input_held(&ecs->game->input, INPUT_UP))
		self->direction = DIRECTION_NORTH;
	else if (input_held(&ecs->game->input, INPUT_DOWN))
		self->direction = DIRECTION_SOUTH;
	else if (input_held(&ecs->game->input, INPUT_LEFT))
		self->direction = DIRECTION_WEST;
	else if (input_held(&ecs->game->input, INPUT_RIGHT))
		self->direction = DIRECTION_EAST;
}

/* Ticks control_move component. */
void
component_control_move_init(ComponentControlMove* self, f32 speed)
{
	self->speed = speed;
}

/* Ticks control_move component. */
void
component_control_move_tick(ComponentControlMove* self, ECS* ecs)
{
	ComponentStun* stun;

	stun = ecs_component_get(ecs, ECS_COMPONENT_STUN, self->component.id);

	if (stun)
		if (stun->isStun)
			return;

	if
	(
		input_held(&ecs->game->input, INPUT_LEFT) ||
		input_held(&ecs->game->input, INPUT_RIGHT) ||
		input_held(&ecs->game->input, INPUT_UP) ||
		input_held(&ecs->game->input, INPUT_DOWN)
	)
	{
		ComponentPhysics* physics;
		vec2 delta;

		physics = ecs_component_get(ecs, ECS_COMPONENT_PHYSICS, self->component.id);

		_direction_update(self, ecs);

		delta[0] = -cos(DIRECTION_ANGLES[self->direction]) * self->speed;
		delta[1] = -sin(DIRECTION_ANGLES[self->direction]) * self->speed;

		physics->velocity[0] += delta[0];
		physics->velocity[1] += delta[1];	
	}
}
