#include "component_control_recall.h"

/* DEPENDENCIES: Physics, ActionReturn, ActionLock */

static void _component_control_recall(ComponentControlRecall* self, ECS* ecs);

/* Find all projectiles that can be recalled. */
/* The first valid one will be recalled. */
/* Valid ones are the ones closest to you and with a different enough angle. */
static void
_component_control_recall(ComponentControlRecall* self, ECS* ecs)
{
	ComponentActionReturn* actionReturn;
	ComponentActionLock* actionLock;

	for (s32 i = 0; i < (s32)ecs->lists[ECS_COMPONENT_ACTION_RETURN].components.count; i++)
	{
		actionReturn = ecs_component_from_index_get(ecs, ECS_COMPONENT_ACTION_RETURN, i);

		if (actionReturn->senderID == self->component.id)
		{
			actionLock = ecs_component_get
			(
				ecs, 
				ECS_COMPONENT_ACTION_LOCK, 
				actionReturn->component.id
			);

			actionLock->isLock = false;
			component_action_lock_unlock(actionLock, ecs);
			component_action_return(actionReturn, ecs);
		}
	}
}

/* Initializes control recall component. */
void
component_control_recall_init(ComponentControlRecall* self, u32 cooldown)
{
	self->cooldownMax = cooldown;
	self->cooldown = self->cooldownMax;
}

/* Ticks control recall.. */
void
component_control_recall_tick(ComponentControlRecall* self, ECS* ecs)
{
	if (self->cooldown > 0)
	{
		self->cooldown--;
		return;
	}

	if (input_press(&ecs->game->input, INPUT_RECALL))
		_component_control_recall(self, ecs);
}
