
#include "utils.h"
#include "director.h"
#include <iostream>
#include <string>

// Constructor
Director::Director(std::string path)
{
	// Crea el objeto que controla los ficheros de recursos
	asset = new Asset(path.substr(0, path.find_last_of("\\/")));

	// Si falta algún fichero no inicia el programa
	if (!setFileList())
	{
		section.name = SECTION_PROG_QUIT;
	}
	else
	{
		section.name = SECTION_PROG_GAME;
		section.subsection = 0;
	}

	// Crea el puntero a la estructura y carga el fichero de configuración
	options = new options_t;
	options->fullScreenMode = 0;
	options->windowSize = 3;
	options->filter = FILTER_NEAREST;
	options->vSync = true;
	options->screenWidth = GAMECANVAS_WIDTH * options->windowSize;
	options->screenHeight =  GAMECANVAS_HEIGHT * options->windowSize;
	options->integerScale = true;
	options->keepAspect = true;

	// Inicializa SDL
	initSDL();

	// Inicializa JailAudio
	initJailAudio();

	// Crea los objetos
	input = new Input(asset->get("gamecontrollerdb.txt"));
	initInput();
	screen = new Screen(window, renderer, options, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT);
	screen->setBorderColor(borderColor);
	debug = new Debug(renderer, screen, asset);
}

Director::~Director()
{
	delete options;
	delete asset;
	delete input;
	delete screen;
	delete debug;

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

// Inicia las variables necesarias para arrancar el programa
void Director::initInput()
{
	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_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);
}

// Inicializa JailAudio
void Director::initJailAudio()
{
	JA_Init(48000, AUDIO_S16, 2);
}

// Arranca SDL y crea la ventana
bool Director::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 a nearest
		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("\n");
	return success;
}

// Crea el indice de ficheros
bool Director::setFileList()
{
	asset->add("/media/font/smb2.png", font);
	asset->add("/media/font/smb2.txt", font);
	asset->add("/media/font/debug.png", font);
	asset->add("/media/font/debug.txt", font);

	asset->add("/data/gamecontrollerdb.txt", data);

	asset->add("/data/room/01.room", room);
	asset->add("/data/room/02.room", room);
	asset->add("/data/room/03.room", room);
	asset->add("/data/room/04.room", room);
	asset->add("/data/room/05.room", room);
	asset->add("/data/room/06.room", room);
	asset->add("/data/room/01.tmx", room);
	asset->add("/data/room/02.tmx", room);
	asset->add("/data/room/03.tmx", room);
	asset->add("/data/room/04.tmx", room);
	asset->add("/data/room/05.tmx", room);
	asset->add("/data/room/06.tmx", room);

	asset->add("/media/tilesets/standard.png", bitmap);

	asset->add("/media/enemies/paco.png", bitmap);
	asset->add("/media/enemies/paco.ani", data);
	asset->add("/media/enemies/chip.png", bitmap);
	asset->add("/media/enemies/chip.ani", data);
	asset->add("/media/enemies/wave.png", bitmap);
	asset->add("/media/enemies/wave.ani", data);
	asset->add("/media/enemies/sigmasua.png", bitmap);
	asset->add("/media/enemies/sigmasua.ani", data);

	asset->add("/media/player/player01.png", bitmap);
	asset->add("/media/player/player01.ani", data);

	asset->add("/media/items/items.png", bitmap);

	asset->add("/media/music/title.ogg", music);
	asset->add("/media/music/game.ogg", music);
	asset->add("/media/music/loading_sound1.ogg", music);
	asset->add("/media/music/loading_sound2.ogg", music);
	asset->add("/media/music/loading_sound3.ogg", music);

	asset->add("/media/sound/item.wav", sound);

	asset->add("/media/logo/jailgames.png", bitmap);
	asset->add("/media/logo/since_1998.png", bitmap);
	asset->add("/media/logo/seagull.png", bitmap);

	asset->add("/media/title/loading_screen1.png", bitmap);
	asset->add("/media/title/loading_screen2.png", bitmap);

	return asset->check();
}

// Obtiene el valor de la variable
Uint8 Director::getSubsection()
{
	return section.subsection;
}

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

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

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

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

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

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

void Director::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;
		}
	}
}