#include "component_behavior_chase.h"

static void _chase(ComponentBehaviorChase* self, ECS* ecs);

/* DEPENDENCIES: Physics */

static void
_chase(ComponentBehaviorChase* self, ECS* ecs)
{
	ComponentPhysics* physics;
	ComponentPhysics* targetPhysics;
	ComponentLevel* level;
	f32 angle;
	f32 speed;

	physics = ecs_component_get(ecs, ECS_COMPONENT_PHYSICS, self->component.id);
	level = ecs_component_get(ecs, ECS_COMPONENT_LEVEL, self->component.id);
	targetPhysics = ecs_component_get(ecs, ECS_COMPONENT_PHYSICS, self->targetID);

	/* this should not happen. */
	if (!targetPhysics)
		return;

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

	speed = self->speed * ((COMPONENT_BEHAVIOR_CHASE_LEVEL_SPEED_MULTIPLIER * (level->value - 1)) + 1);
	speed = MAX(speed, COMPONENT_BEHAVIOR_CHASE_SPEED_MAX);

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

	self->soundTimer--;

	if (self->soundTimer == 0)
	{
		ComponentGameEntityType* gameEntityType;

		gameEntityType = ecs_component_get(ecs, ECS_COMPONENT_GAME_ENTITY_TYPE, self->component.id);

		switch (gameEntityType->type)
		{
			case GAME_ENTITY_CUSTARPEDO:
				sound_play(&ecs->game->resources.sounds[SOUND_CUSTARPEDO_FLY], 0);
				break;
			default:
				break;
		}

		self->soundTimer = COMPONENT_BEHAVIOR_CHASE_SOUND_TIMER_MAX;
	}
}

/* Sets behavior_chase component info. */
void
component_behavior_chase_init(ComponentBehaviorChase* self, f32 speed, u32 targetID)
{
	self->speed = speed;
	self->targetID = targetID;
	self->soundTimer = COMPONENT_BEHAVIOR_CHASE_SOUND_TIMER_MAX;
}

/* Ticks behavior_chase component. */
void
component_behavior_chase_tick(ComponentBehaviorChase* self, ECS* ecs)
{	
	_chase(self, ecs);
}
