#include "component_circle_collision.h"

static void _collision_check(ComponentCircleCollision* self, ECS* ecs);

/* Check collisions. */
static void
_collision_check(ComponentCircleCollision* self, ECS* ecs)
{
	for (s32 i = 0; i < (s32)ecs->lists[ECS_COMPONENT_CIRCLE_COLLISION].components.count; i++)
	{
		ComponentCircleCollision* circleCollision;

		circleCollision = vector_get(&ecs->lists[ECS_COMPONENT_CIRCLE_COLLISION].components, i);

		if (circleCollision->component.isDisabled)
			continue;

		if (circleCollision->component.id == self->component.id)
			continue;

		if (circle_collide(&self->circle, &circleCollision->circle))
			vector_push(&self->collisions, &circleCollision->component.id);
	}
}

/* Sets circle_collision component info. */
void
component_circle_collision_init(ComponentCircleCollision* self, ECS* ecs, f32 radius)
{
	ComponentPhysics* physics;

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

	glm_vec2_copy(physics->position, self->circle.position);

	self->circle.position[0] = physics->position[0];
	self->circle.position[1] = physics->position[1];

	self->circle.radius = radius;
}

/* Adds a circle_collision component. */
void
component_circle_collision_add(ComponentCircleCollision* self, ECS* ecs)
{
	vector_init(&self->collisions, sizeof(u32));
}

/* Deletes a circle_collision component. */
void
component_circle_collision_delete(ComponentCircleCollision* self, ECS* ecs)
{
	vector_free(&self->collisions);
}

/* Ticks circle_collision component. */
void
component_circle_collision_tick(ComponentCircleCollision* self, ECS* ecs)
{
	if (self->collisions.count > 0)
		vector_clear(&self->collisions);

	ComponentPhysics* physics;

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

	self->circle.position[0] = physics->position[0];
	self->circle.position[1] = physics->position[1];

	_collision_check(self, ecs);
}
