#include "component_action_gripped.h"

/* DEPENDENCIES: GameObject */

/* Gripped component. These objects can be gripped by entities with ActionGrip components. */

/* What if this object is ungripped (i.e., the gripped is destroyed?) This happens... */
static void
_component_action_gripped_ungrip(ComponentActionGripped* self, ECS* ecs)
{
	/* Just kill yourself, lol! */
	ecs_entity_delete(ecs, self->component.id);
}

/* When this object is being gripped, do this. */
static void
_component_action_gripped_set(ComponentActionGripped* self, ECS* ecs)
{
	ComponentGameObject* gameObject;
	ComponentGameObject* gripperGameObject;
	ComponentSprite* sprite;
	ComponentPhysics* physics;
	ComponentPhysics* gripperPhysics;

	gripperGameObject = ecs_component_get(ecs, ECS_COMPONENT_GAME_OBJECT, self->gripperID);

	/* If we can't find the gripper game object, ungrip this. */
	if (!gripperGameObject)
	{
		_component_action_gripped_ungrip(self, ecs);
		return;
	}

	gameObject = ecs_component_get(ecs, ECS_COMPONENT_GAME_OBJECT, self->component.id);
	physics = ecs_component_get(ecs, ECS_COMPONENT_PHYSICS, self->component.id);
	gripperPhysics = ecs_component_get(ecs, ECS_COMPONENT_PHYSICS, self->gripperID);
	sprite = ecs_component_get(ecs, ECS_COMPONENT_SPRITE, self->component.id);

	glm_vec3_copy(gripperPhysics->position, physics->position);

	glm_vec3_copy(gripperPhysics->velocity, physics->velocity);

	gameObject->height = gripperGameObject->height + (physics->size[1] * 2);
	
	sprite->offset[2] = gripperPhysics->position[2] + COMPONENT_ACTION_GRIPPED_Z_OFFSET;
	
	gameObject->isBounce = gripperGameObject->isBounce;
	gameObject->isAffectedByGravity = gripperGameObject->isAffectedByGravity;
}

/* Runs on add action gripped component. */
void
component_action_gripped_add(ComponentActionGripped* self, ECS* ecs)
{
	self->timer = COMPONENT_ACTION_GRIPPED_TIMER;
}

/* Ticks grip component. */
void
component_action_gripped_tick(ComponentActionGripped* self, ECS* ecs)
{
	if (self->timer > 0)
	{
		self->timer--;
		
		if (self->timer <= 0)
		{
			self->timer = 0;
			self->isAbleToBeGripped = true;
		}

		return;
	}
	
	if (self->isGripped)
		_component_action_gripped_set(self, ecs);
}
