#include "component_action_return.h"

/* DEPENDENCIES: Physics, ActionDeleteOnTouchEntity */

/* Adds a action_return component. */
void
component_action_return_add(ComponentActionReturn* self, ECS* ecs)
{
	ComponentActionDeleteOnTouchEntity* actionDeleteOnTouchEntity;
	
	actionDeleteOnTouchEntity = ecs_component_add(ecs, ECS_COMPONENT_ACTION_DELETE_ON_TOUCH_ENTITY, self->component.id);

	actionDeleteOnTouchEntity->component.isDisabled = true;
}

/* Adds a action_return component. */
void
component_action_return_delete(ComponentActionReturn* self, ECS* ecs)
{
	ecs_component_delete(ecs, ECS_COMPONENT_ACTION_DELETE_ON_TOUCH_ENTITY, self->component.id);
}

/* Initializes action_return component. */
void 
component_action_return_init
(
	ComponentActionReturn* self, 
	ECS* ecs, 
	f32 speed, 
	f32 multiplier,
	f32 velocityMax, 
	u32 lifetime, 
	u32 senderID
)
{
	ComponentActionDeleteOnTouchEntity* actionDeleteOnTouchEntity;

	actionDeleteOnTouchEntity = ecs_component_get(ecs, ECS_COMPONENT_ACTION_DELETE_ON_TOUCH_ENTITY, self->component.id);

	component_action_delete_on_touch_entity_init(actionDeleteOnTouchEntity, ecs, senderID);

	self->speed = speed;
	self->multiplier = multiplier;
	self->velocityMax = velocityMax;
	self->lifetimeMax = lifetime;
	self->lifetime = self->lifetimeMax;
	self->senderID = senderID;
}

/* Sets the object to return. */
void
component_action_return(ComponentActionReturn* self, ECS* ecs)
{
	ComponentPhysics* physics;
	ComponentActionDeleteOnTouchEntity* actionDeleteOnTouchEntity;
	ComponentActionDamage* actionDamage;

	actionDeleteOnTouchEntity = ecs_component_get
	(	
		ecs, 
		ECS_COMPONENT_ACTION_DELETE_ON_TOUCH_ENTITY, 
		self->component.id
	);

	physics = ecs_component_get(ecs, ECS_COMPONENT_PHYSICS, self->component.id);
	actionDamage = ecs_component_get(ecs, ECS_COMPONENT_ACTION_DAMAGE, self->component.id);
	
	self->lifetime = 0;
	physics->velocityMax = self->velocityMax;
	self->isReturning = true;
	actionDeleteOnTouchEntity->component.isDisabled = false;
	vector_clear(&actionDamage->damageEntries);
}

/* Ticks action_return component. */
/* Rapidly accelerates entity towards sender. */
void 
component_action_return_tick(ComponentActionReturn* self, ECS* ecs)
{
	f32 angle;
	f32 speed;
	ComponentPhysics* senderPhysics;
	ComponentPhysics* physics;

	if (self->lifetime > 0)
	{
		self->lifetime--;

		if (self->lifetime <= 0)
			component_action_return(self, ecs);
	}

	if (!self->isReturning)
		return;

	self->timer++;

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

	angle = ATAN
	(
		physics->position[0], 
		senderPhysics->position[0], 
		physics->position[1], 
		senderPhysics->position[1]
	);

	speed = self->speed * (self->timer * self->multiplier);

	physics->velocity[0] = cos(angle) * speed;
	physics->velocity[1] = sin(angle) * speed;
}
