#include "game.h"

Game game;

static void _game_tick(Game* self);
static void _game_draw(Game* self);
static void _game_quit(Game* self);

/* Quits game. */
static void
_game_quit(Game* self)
{
	state_free(&self->state);

	ecs_free(&self->ecs);

	window_free(&self->window);

	sdl_quit();

	memset(self, '\0', sizeof(Game));

	exit(EXIT_SUCCESS);
}

/* Main game tick function. */
static void
_game_tick(Game* self)
{
	if (!self->isPaused)
		ecs_tick(&self->ecs);

	input_update(&self->input);

	if (input_press(&self->input, INPUT_PAUSE))
	{
		sound_play(&self->resources.sounds[SOUND_SELECT], SOUND_PRIORITY);
		self->isPaused = !self->isPaused;
	}

	if (event_press(&self->input.event, EVENT_QUIT))
		_game_quit(self);
}

/* Main game draw function. */
static void
_game_draw(Game* self)
{
	renderer_update(&self->renderer);

	renderer_clear_color_set(&self->renderer, (f32*)RENDERER_CLEAR_COLOR);

	renderer_clear(&self->renderer);

	ecs_draw(&self->ecs);

	renderer_present(&self->renderer);
}

/* Initializes game. */
void
game_init(Game* self)
{
	memset(self, '\0', sizeof(Game));

	RANDOM_SEED_SET(time(NULL));

	resource_shader_read(&self->resources);

	sdl_init();

	window_init
	(
		&self->window, 
		STRING_WINDOW_TITLE,
		(s32*)WINDOW_SIZE,
		WINDOW_FLAGS
	);

	renderer_init(&self->renderer, &self->window, CAMERA_ORTHOGRAPHIC, WORLD_SIZE);
	renderer_clear_color_set(&self->renderer, (f32*)RENDERER_CLEAR_COLOR);

	ecs_init(&self->ecs, self);

	state_init(&self->state, self, STATE_PLAY);
}

/* Main game loop. */
void
game_loop(Game* self)
{
	tick_update(&self->tick);

	while (self->tick.cum > 16)
	{
		_game_tick(self);
		
		self->tick.cum -= 16;
	}

	_game_draw(self);
}
