#include "prog.h"

// Constructor
Prog::Prog(std::string executablePath)
{
	// Establece las opciones por defecto
	options = new options_t;
	options->fullScreenMode = 0;
	options->windowSize = 2;
	options->filter = FILTER_NEAREST;
	options->vSync = true;
	options->screenWidth = GAME_WIDTH * options->windowSize;
	options->screenHeight = GAME_HEIGHT * options->windowSize;
	options->integerScale = true;
	options->keepAspect = true;

	// Inicia las librerias
	initSDL();
	initJailAudio();

	// Crea los objetos
	asset = new Asset(executablePath.substr(0, executablePath.find_last_of("\\/")));
	if (!setFileList())
	{
		section.name = SECTION_PROG_QUIT;
	}
	else
	{
		section.name = SECTION_PROG_LOGO;
	}
	input = new Input(asset->get("gamecontrollerdb.txt"));
	screen = new Screen(window, renderer, options);

	// Controles
	input->bindKey(INPUT_UP, SDL_SCANCODE_UP);
	input->bindKey(INPUT_DOWN, SDL_SCANCODE_DOWN);
	input->bindKey(INPUT_LEFT, SDL_SCANCODE_LEFT);
	input->bindKey(INPUT_RIGHT, SDL_SCANCODE_RIGHT);
	input->bindKey(INPUT_ACCEPT, SDL_SCANCODE_RETURN);
	input->bindKey(INPUT_CANCEL, SDL_SCANCODE_ESCAPE);
	input->bindKey(INPUT_BUTTON_1, SDL_SCANCODE_SPACE);
	input->bindKey(INPUT_BUTTON_2, SDL_SCANCODE_D);
	input->bindKey(INPUT_BUTTON_3, SDL_SCANCODE_R);
	input->bindKey(INPUT_BUTTON_PAUSE, SDL_SCANCODE_ESCAPE);
	input->bindKey(INPUT_BUTTON_ESCAPE, SDL_SCANCODE_ESCAPE);

	input->bindGameControllerButton(INPUT_UP, SDL_CONTROLLER_BUTTON_DPAD_UP);
	input->bindGameControllerButton(INPUT_DOWN, SDL_CONTROLLER_BUTTON_DPAD_DOWN);
	input->bindGameControllerButton(INPUT_LEFT, SDL_CONTROLLER_BUTTON_DPAD_LEFT);
	input->bindGameControllerButton(INPUT_RIGHT, SDL_CONTROLLER_BUTTON_DPAD_RIGHT);
	input->bindGameControllerButton(INPUT_ACCEPT, SDL_CONTROLLER_BUTTON_B);
	input->bindGameControllerButton(INPUT_CANCEL, SDL_CONTROLLER_BUTTON_A);
	input->bindGameControllerButton(INPUT_BUTTON_1, SDL_CONTROLLER_BUTTON_B);
	input->bindGameControllerButton(INPUT_BUTTON_PAUSE, SDL_CONTROLLER_BUTTON_GUIDE);
	input->bindGameControllerButton(INPUT_BUTTON_ESCAPE, SDL_CONTROLLER_BUTTON_GUIDE);
}

Prog::~Prog()
{
	delete options;
	delete asset;
	delete input;
	delete screen;

	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);
	SDL_Quit();
}

// Inicializa JailAudio
void Prog::initJailAudio()
{
	JA_Init(44100, AUDIO_S16, 2);
}

// Arranca SDL y crea la ventana
bool Prog::initSDL()
{
	// Indicador de éxito
	bool success = true;

	// Inicializa SDL
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER | SDL_INIT_AUDIO) < 0)
	{
		printf("SDL could not initialize!\nSDL Error: %s\n", SDL_GetError());
		success = false;
	}
	else
	{
		// Inicia el generador de numeros aleatorios
		std::srand(static_cast<unsigned int>(SDL_GetTicks()));

		// Establece el filtro de la textura
		if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, std::to_string(options->filter).c_str()))
		{
			printf("Warning: Nearest texture filtering not enabled!\n");
		}

		// Crea la ventana
		window = SDL_CreateWindow(WINDOW_CAPTION, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, options->screenWidth, options->screenHeight, SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI);
		if (window == NULL)
		{
			printf("Window could not be created!\nSDL Error: %s\n", SDL_GetError());
			success = false;
		}
		else
		{
			// Crea un renderizador para la ventana. El vsync se activa en funcion de las opciones
			if (options->vSync)
				renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
			else
				renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

			if (renderer == NULL)
			{
				printf("Renderer could not be created!\nSDL Error: %s\n", SDL_GetError());
				success = false;
			}
			else
			{
				// Inicializa el color de renderizado
				SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF);

				// Establece el tamaño del buffer de renderizado
				SDL_RenderSetLogicalSize(renderer, options->screenWidth, options->screenHeight);

				// Establece el modo de mezcla
				SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
			}
		}
	}

	printf("SDL is running...\n");
	return success;
}

// Crea el indice de ficheros de recursos
bool Prog::setFileList()
{
	// Ficheros del mapa
	asset->add("/data/map/01.map", data);
	asset->add("/data/map/01.tmx", data);
	asset->add("/data/map/02.map", data);
	asset->add("/data/map/02.tmx", data);
	asset->add("/data/map/03.map", data);
	asset->add("/data/map/03.tmx", data);
	asset->add("/data/map/surface.png", bitmap);

	// Ficheros de configuración
	asset->add("/data/config.bin", data, false);
	asset->add("/data/input/gamecontrollerdb.txt", data);

	// Ficheros del jugador
	asset->add("/data/player/player.png", bitmap);
	asset->add("/data/player/player.ani", data);

	// Ficheros de sonido
	asset->add("/data/sound/sound_player_coin.wav", sound);
	asset->add("/data/sound/sound_player_death.wav", sound);
	asset->add("/data/sound/sound_drop_enemy.wav", sound);
	asset->add("/data/sound/sound_drop_splat.wav", sound);
	asset->add("/data/sound/sound_player_jump.wav", sound);
	asset->add("/data/sound/sound_menu_logo.wav", sound);
	asset->add("/data/sound/sound_menu_start.wav", sound);

	// Ficheros con musica
	asset->add("/data/music/music_title.ogg", music);
	asset->add("/data/music/music_surface.ogg", music);
	asset->add("/data/music/music_volcano.ogg", music);

	// Ficheros de fuentes de texto
	asset->add("/data/font/debug.png", font);
	asset->add("/data/font/debug.txt", font);
	asset->add("/data/font/dogica.png", font);
	asset->add("/data/font/dogica.txt", font);

	// Ficheros de enemigos
	asset->add("/data/actors/enemies/walking_eye.png", bitmap);
	asset->add("/data/actors/enemies/walking_eye.ani", data);
	asset->add("/data/actors/enemies/bug.png", bitmap);
	asset->add("/data/actors/enemies/bug.ani", data);
	asset->add("/data/actors/enemies/flying_eye.png", bitmap);
	asset->add("/data/actors/enemies/flying_eye.ani", data);
	asset->add("/data/actors/enemies/flying_eye_horn.png", bitmap);
	asset->add("/data/actors/enemies/flying_eye_horn.ani", data);

	// Ficheros del logo
	asset->add("/data/logo/logo.png", bitmap);

	// Ficheros de la intro
	asset->add("/data/intro/intro.png", bitmap);
	asset->add("/data/intro/intro.ani", data);

	return asset->check();
}

// Obtiene el valor de la variable
Uint8 Prog::getSection()
{
	return section.name;
}

// Establece el valor de la variable
void Prog::setSection(section_t section)
{
	this->section = section;
}

// Ejecuta la seccion de juego con el logo
void Prog::runLogo()
{
	logo = new Logo(renderer, screen, asset);
	setSection(logo->run());
	delete logo;
}

// Ejecuta la seccion de juego de la introducción
void Prog::runIntro()
{
	intro = new Intro(renderer, screen, asset);
	setSection(intro->run());
	delete intro;
}

// Ejecuta la seccion de juego con el titulo y los menus
void Prog::runTitle()
{
	title = new Title(renderer, screen, asset, input);
	setSection(title->run());
	delete title;
}

// Ejecuta la seccion de juego donde se juega
void Prog::runGame()
{
	game = new Game(renderer, screen, asset, input);
	setSection(game->run());
	delete game;
}

void Prog::run()
{
	// Bucle principal
	while (!(getSection() == SECTION_PROG_QUIT))
	{
		switch (getSection())
		{
		case SECTION_PROG_LOGO:
			runLogo();
			break;
		case SECTION_PROG_INTRO:
			runIntro();
			break;
		case SECTION_PROG_TITLE:
			runTitle();
			break;
		case SECTION_PROG_GAME:
			runGame();
			break;
		}
	}
}