#include "state.h"

static void _state_set(State* state, StateType type);

/* Sets the game state. */
static void
_state_set(State* state, StateType type)
{
	state->type = type;

	resource_shader_state_init
	(
		&state->game->resources, 
		STATE_SHADERS[state->type], 
		STATE_SHADER_COUNT[state->type]
	);

	resource_texture_state_init
	(
		&state->game->resources, 
		STATE_TEXTURES[state->type], 
		STATE_TEXTURE_COUNT[state->type]
	);

	resource_font_state_init
	(
		&state->game->resources, 
		STATE_FONTS[state->type], 
		STATE_FONT_COUNT[state->type]
	);

	resource_sound_state_init
	(
		&state->game->resources, 
		STATE_SOUNDS[state->type], 
		STATE_SOUND_COUNT[state->type]
	);

	resource_music_state_init
	(
		&state->game->resources, 
		STATE_MUSIC[state->type], 
		STATE_MUSIC_COUNT[state->type]
	);

	switch (state->type)
	{
		case STATE_PLAY:
			play_init(&state->play, state);
			break;
		default:
			break;
	}
}

/* Initializes game state; does not free past resources. */
void
state_init(State* state, Game* game, StateType type)
{
	memset(state, '\0', sizeof(State));

	state->game = game;

	_state_set(state, type);
}

/* Frees current stare resources. */
void
state_free(State* state)
{
	ecs_clear(&state->game->ecs);

	resource_shader_state_free
	(
		&state->game->resources, 
		STATE_SHADERS[state->type], 
		STATE_SHADER_COUNT[state->type]
	);

	resource_texture_state_free
	(
		&state->game->resources, 
		STATE_TEXTURES[state->type], 
		STATE_TEXTURE_COUNT[state->type]
	);

	resource_font_state_free
	(
		&state->game->resources, 
		STATE_FONTS[state->type], 
		STATE_FONT_COUNT[state->type]
	);

	resource_sound_state_free
	(
		&state->game->resources, 
		STATE_SOUNDS[state->type], 
		STATE_SOUND_COUNT[state->type]
	);

	resource_music_state_free
	(
		&state->game->resources, 
		STATE_MUSIC[state->type], 
		STATE_MUSIC_COUNT[state->type]
	);
}

/* Changes game state and initializes new resources. */
void
state_change(State* state, StateType type)
{
	state_free(state);
	_state_set(state, type);
}
