#include "component_action_follow.h"

/* DEPENDENCIES: Sprite */

static void _follow(ComponentActionFollow* self, ECS* ecs);

/* When this object is being gripped, do this. */
static void
_follow(ComponentActionFollow* self, ECS* ecs)
{
	ComponentSprite* followSprite;
	ComponentSprite* sprite;

	sprite = ecs_component_get(ecs, ECS_COMPONENT_SPRITE, self->component.id);
	followSprite = ecs_component_get(ecs, ECS_COMPONENT_SPRITE, self->followID);

	/* If we can't find the followed sprite, kys. */
	if (!followSprite)
	{
		ecs_entity_delete(ecs, self->component.id);
		return;
	}

	glm_vec3_copy(followSprite->position, sprite->position);
	glm_vec3_add(sprite->position, followSprite->offset, sprite->position);

	sprite->position[0] += -cos(sprite->rotation) * self->offset;
	sprite->position[1] += -sin(sprite->rotation) * self->offset;
	sprite->position[2] += COMPONENT_ACTION_FOLLOW_Z_OFFSET;
}

/* Intializes the follow component. */
void
component_action_follow_init(ComponentActionFollow* self, u32 followID, f32 offset)
{
	self->followID = followID;
	self->offset = offset;
}

/* Ticks grip component. */
void
component_action_follow_tick(ComponentActionFollow* self, ECS* ecs)
{
	_follow(self, ecs);
}
