#include "title.h"

// Constructor
Title::Title(SDL_Renderer *renderer, Screen *screen, Asset *asset, Input *input)
{
	// Copia los punteros
	this->renderer = renderer;
	this->screen = screen;
	this->asset = asset;
	this->input = input;

	// Reserva memoria para los punteros
	eventHandler = new SDL_Event();
	texture = new LTexture(renderer, asset->get("intro.png"));
	sprite = new AnimatedSprite(texture, renderer, asset->get("intro.ani"));
	sprite->setCurrentAnimation("menu");
	text = new Text(asset->get("debug.png"), asset->get("debug.txt"), renderer);
	music = JA_LoadMusic(asset->get("music_title.ogg").c_str());
	menu = new Menu(renderer, asset, input, asset->get("title.men"));

	// Inicializa variables
	section = {SECTION_PROG_TITLE, 0};
	ticks = 0;
	ticksSpeed = 15;
}

// Destructor
Title::~Title()
{
	renderer = nullptr;
	screen = nullptr;
	asset = nullptr;

	delete eventHandler;
	eventHandler = nullptr;

	texture->unload();
	delete texture;
	texture = nullptr;

	delete sprite;
	sprite = nullptr;

	delete text;
	text = nullptr;

	delete menu;
	menu = nullptr;

	JA_DeleteMusic(music);
}

// Actualiza las variables
void Title::update()
{
	// Comprueba que la diferencia de ticks sea mayor a la velocidad del juego
	if (SDL_GetTicks() - ticks > ticksSpeed)
	{
		// Actualiza el contador de ticks
		ticks = SDL_GetTicks();

		// Comprueba los eventos que hay en la cola
		while (SDL_PollEvent(eventHandler) != 0)
		{
			// Evento de salida de la aplicación
			if (eventHandler->type == SDL_QUIT)
			{
				section.name = SECTION_PROG_QUIT;
				break;
			}

			// Cualquier tecla pulsada
			/*if ((eventHandler->type == SDL_KEYDOWN) || (eventHandler->type == SDL_JOYBUTTONDOWN))
			{
				section.name = SECTION_PROG_GAME;
				section.subsection = 0;
			}*/
		}
		sprite->animate();
		menu->update();
		checkMenu();
	}
}

// Dibuja en pantalla
void Title::render()
{
	// Prepara para empezar a dibujar en la textura de juego
	screen->start();

	// Limpia la pantalla
	screen->clean();

	// Dibuja los objetos
	sprite->render();
	//const std::string text = TEXT_COPYRIGHT + " (" + VERSION + ")";
	this->text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, 205, TEXT_COPYRIGHT, 0, {255, 93, 4});
	menu->render();

	// Vuelca el contenido del renderizador en pantalla
	screen->blit();
}

// Bucle principal
section_t Title::run()
{
	JA_PlayMusic(music);

	while (section.name == SECTION_PROG_TITLE)
	{
		update();
		render();
	}

	return section;

	JA_StopMusic();
}

// Comprueba el menu
void Title::checkMenu()
{
	const int menu = this->menu->getItemSelected();

	switch (menu)
	{
	case 0:
		section.name = SECTION_PROG_GAME;
		break;

	case 2:
		section.name = SECTION_PROG_QUIT;
		break;

	default:
		break;
	}
}