#include "component_action_on_combat_hide.h"

/* 
	DEPENDENCIES:
	ActionSpawn
	GameObject
*/

static void _hide(ComponentActionOnCombatHide* self, ECS* ecs);
static void _unhide(ComponentActionOnCombatHide* self, ECS* ecs);

/* "Hides" this component (disables drawing + collisions) */
static void
_hide(ComponentActionOnCombatHide* self, ECS* ecs)
{
	ComponentGameObject* gameObject;
	ComponentSprite* sprite;
	ComponentSprite* shadowSprite;
	ComponentPhysics* physics;

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

	gameObject->component.isDisabled = true;
	physics->component.isDisabled = true;
	sprite->component.isDisabled = true;
	shadowSprite->component.isDisabled = true;

	vector_clear(&physics->collisions);
}

/* "Unhides" this component (enables drawing + collisions) */
static void
_unhide(ComponentActionOnCombatHide* self, ECS* ecs)
{
	ComponentGameObject* gameObject;
	ComponentSprite* sprite;
	ComponentSprite* shadowSprite;
	ComponentPhysics* physics;

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

	gameObject->component.isDisabled = false;
	physics->component.isDisabled = false;
	sprite->component.isDisabled = false;
	shadowSprite->component.isDisabled = false;
}

/* Initializes ActionOnCombatHide component. */
void
component_action_on_combat_hide_init(ComponentActionOnCombatHide* self, ECS* ecs, u32 spawnID, u32 timer)
{
	self->spawnID = spawnID;
	self->timerMax = timer;
	self->timer = self->timerMax;
}

/* Ticks action hide on spawn component. */
void
component_action_on_combat_hide_tick(ComponentActionOnCombatHide* self, ECS* ecs)
{
	ComponentActionSpawn* actionSpawn;

	if (self->isChanging)
	{
		self->timer--;

		if (self->timer == 0)
		{
			self->isChanging = false;
			self->isHide = !self->isHide;

			if (self->isHide)
				_hide(self, ecs);
			else
				_unhide(self, ecs);

			self->isUnhiding = false;
			self->isHiding = false;
		}
		return;
	}

	actionSpawn = ecs_component_get(ecs, ECS_COMPONENT_ACTION_SPAWN, self->spawnID);

	if (self->isHide)
	{
		if (!actionSpawn->isCombat)
		{
			self->isUnhiding = true;
			self->timer = self->timerMax;
			self->isChanging = true;
		}
	}
	else
	{
		if (actionSpawn->isCombat)
		{
			self->isHiding = true;
			self->timer = self->timerMax;
			self->isChanging = true;
		}
	}

	
}
