#include "component_action_wave.h"

static void _timer_set(ComponentActionWave* self, ECS* ecs);
static void _wave_add(ComponentActionWave* self, ECS* ecs);

/* Sets the wave timer. */
static void
_timer_set(ComponentActionWave* self, ECS* ecs)
{
	ComponentLevel* level;
	
	level = ecs_component_get(ecs, ECS_COMPONENT_LEVEL, self->component.id);

	self->timer = COMPONENT_ACTION_WAVE_SPAWN_TIMER_BASE;

	self->timer -= ((level->value - 1) * COMPONENT_ACITON_WAVE_SPAWN_TIMER_LEVEL_MULTIPLIER);
	self->timer = MIN(self->timer, COMPONENT_ACTION_WAVE_SPAWN_TIMER_MIN);
}

/* Adds a wave to the spawn component. */
static void
_wave_add(ComponentActionWave* self, ECS* ecs)
{
	ComponentActionSpawn* actionSpawn;
	ComponentLevel* level;

	actionSpawn = ecs_component_get(ecs, ECS_COMPONENT_ACTION_SPAWN, self->component.id);
	level = ecs_component_get(ecs, ECS_COMPONENT_LEVEL, self->component.id);

	component_action_spawn_wave_add(actionSpawn, ecs, (SpawnWave*)&SPAWN_WAVES[self->index]);

	self->index++;

	/* restart if past all waves */
	if (self->index >= COMPONENT_ACTION_WAVE_COUNT)
	{
		self->index = 0;
		level->value++;
	}

	_timer_set(self, ecs);

	self->timer += SPAWN_WAVES[self->index].timer;
}

/* Runs on add wave. */
void
component_action_wave_add(ComponentActionWave* self, ECS* ecs)
{
	_timer_set(self, ecs);
}

/* Ticks action_wave component. */
void
component_action_wave_tick(ComponentActionWave* self, ECS* ecs)
{
	if (self->timer > 0)
	{
		self->timer--;

		if (self->timer == 0)
			self->isSpawnWave = true;
	}

	if (self->isSpawnWave)
	{
		self->timer = 0;
		self->isSpawnWave = false;

		_wave_add(self, ecs);
	}
}
