#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();
	loadTextureFromFile(texture, asset->get("intro.png"), renderer);
	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());

	// 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;

    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();
	}
}

// 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();
	//text->writeCentered(160, 200, "@2016,2022 JAILDESIGNER & JAILBROTHER (v0.6)", -1);
	const color_t color = {179,83,71};
	text->writeDX(TXT_CENTER|TXT_COLOR,160, 200, "@2016,2022 JAILDESIGNER & JAILBROTHER (v0.6)", -1, color);

	// 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();
}
