
#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;
	}

	// Inicializa variables desde el fichero de configuración
	loadConfig();

	// 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);
	screen->setVideoMode(options->fullScreenMode);
	debug = new Debug(renderer, screen, asset);
}

Director::~Director()
{
	// Guarda las opciones de configuración
	saveConfig();

	// Libera la memoria
	delete options;
	delete asset;
	delete input;
	delete screen;
	delete debug;

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

// Carga el fichero de configuración
bool Director::loadConfig()
{
	// Crea el puntero a la estructura de opciones e inicializa valores
	options = new options_t;
	options->fullScreenMode = 0;
	options->windowSize = 3;
	options->filter = FILTER_NEAREST;
	options->vSync = true;
	options->integerScale = true;
	options->keepAspect = true;
	options->borderEnabled = false;
	options->borderSize = 0.1f;

	// Indicador de éxito en la carga
	bool success = true;

	// Variables para manejar el fichero
	std::string line;
	std::ifstream file(asset->get("config.txt"));

	// Si el fichero se puede abrir
	if (file.good())
	{
		// Procesa el fichero linea a linea
		printf("Reading file config.txt\n");
		while (std::getline(file, line))
		{
			// Comprueba que la linea no sea un comentario
			if (line.substr(0, 1) != "#")
			{
				// Encuentra la posición del caracter '='
				int pos = line.find("=");
				// Procesa las dos subcadenas
				if (!setOptions(options, line.substr(0, pos), line.substr(pos + 1, line.length())))
				{
					printf("Warning: file %s\n, unknown parameter \"%s\"\n", "config.txt", line.substr(0, pos).c_str());
					success = false;
				}
			}
		}

		// Cierra el fichero
		printf("Closing file config.txt\n\n");
		file.close();
	}

	// El fichero no existe
	else
	{ // Crea el fichero con los valores por defecto
		saveConfig();
	}

	// Aplica opciones
	if (options->borderEnabled)
	{
		const int incWidth = GAMECANVAS_WIDTH * options->borderSize;
		const int incHeight = GAMECANVAS_HEIGHT * options->borderSize;
		options->screenWidth = (GAMECANVAS_WIDTH + incWidth) * options->windowSize;
		options->screenHeight = (GAMECANVAS_HEIGHT + incHeight) * options->windowSize;
	}
	else
	{
		options->screenWidth = GAMECANVAS_WIDTH * options->windowSize;
		options->screenHeight = GAMECANVAS_HEIGHT * options->windowSize;
	}

	return success;
}

// Guarda el fichero de configuración
bool Director::saveConfig()
{
	bool success = true;

	// Crea y abre el fichero de texto
	std::ofstream file(asset->get("config.txt"));

	// Escribe en el fichero
	if (options->fullScreenMode == 0)
	{
		file << "fullScreenMode=0\n";
	}

	else if (options->fullScreenMode == SDL_WINDOW_FULLSCREEN)
	{
		file << "fullScreenMode=SDL_WINDOW_FULLSCREEN\n";
	}

	else if (options->fullScreenMode == SDL_WINDOW_FULLSCREEN_DESKTOP)
	{
		file << "fullScreenMode=SDL_WINDOW_FULLSCREEN_DESKTOP\n";
	}

	file << "windowSize=" + std::to_string(options->windowSize) + "\n";

	if (options->filter == FILTER_NEAREST)
	{
		file << "filter=FILTER_NEAREST\n";
	}
	else
	{
		file << "filter=FILTER_LINEAL\n";
	}

	file << "vSync=" + boolToString(options->vSync) + "\n";
	file << "integerScale=" + boolToString(options->integerScale) + "\n";
	file << "keepAspect=" + boolToString(options->keepAspect) + "\n";
	file << "borderEnabled=" + boolToString(options->borderEnabled) + "\n";
	file << "borderSize=" + std::to_string(options->borderSize) + "\n";

	// Cierra el fichero
	file.close();

	return success;
}

// Asigna variables a partir de dos cadenas
bool Director::setOptions(options_t *options, std::string var, std::string value)
{
	// Indicador de éxito en la asignación
	bool success = true;

	if (var == "fullScreenMode")
	{
		if (value == "SDL_WINDOW_FULLSCREEN_DESKTOP")
		{
			options->fullScreenMode = SDL_WINDOW_FULLSCREEN_DESKTOP;
		}
		else if (value == "SDL_WINDOW_FULLSCREEN")
		{
			options->fullScreenMode = SDL_WINDOW_FULLSCREEN;
		}
		else
		{
			options->fullScreenMode = 0;
		}
	}

	else if (var == "windowSize")
	{
		options->windowSize = std::stoi(value);
		if ((options->windowSize < 1) || (options->windowSize > 4))
		{
			options->windowSize = 3;
		}
	}

	else if (var == "filter")
	{
		if (value == "FILTER_LINEAL")
		{
			options->filter = FILTER_LINEAL;
		}
		else
		{
			options->filter = FILTER_NEAREST;
		}
	}

	else if (var == "vSync")
	{
		options->vSync = stringToBool(value);
	}

	else if (var == "integerScale")
	{
		options->integerScale = stringToBool(value);
	}

	else if (var == "keepAspect")
	{
		options->keepAspect = stringToBool(value);
	}

	else if (var == "borderEnabled")
	{
		options->borderEnabled = stringToBool(value);
	}

	else if (var == "borderSize")
	{
		options->borderSize = std::stof(value);
		if (options->borderSize < 0.0f || options->borderSize > 0.5f)
		{
			options->borderSize = 0.1f;
		}
	}

	else if (var == "")
	{
	}

	else
	{
		success = false;
	}

	return success;
}

// 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 == nullptr)
		{
			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 == nullptr)
			{
				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("/data/font/smb2.png", font);
	asset->add("/data/font/smb2.txt", font);
	asset->add("/data/font/debug.png", font);
	asset->add("/data/font/debug.txt", font);

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

	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/07.room", room);
	asset->add("/data/room/08.room", room);
	asset->add("/data/room/09.room", room);
	asset->add("/data/room/10.room", room);
	asset->add("/data/room/11.room", room);
	asset->add("/data/room/12.room", room);
	asset->add("/data/room/13.room", room);
	asset->add("/data/room/14.room", room);
	asset->add("/data/room/15.room", room);
	asset->add("/data/room/16.room", room);
	asset->add("/data/room/17.room", room);
	asset->add("/data/room/18.room", room);
	asset->add("/data/room/19.room", room);
	asset->add("/data/room/20.room", room);
	asset->add("/data/room/21.room", room);
	asset->add("/data/room/22.room", room);
	asset->add("/data/room/23.room", room);
	asset->add("/data/room/24.room", room);
	asset->add("/data/room/25.room", room);
	asset->add("/data/room/26.room", room);
	asset->add("/data/room/27.room", room);
	asset->add("/data/room/28.room", room);
	asset->add("/data/room/29.room", room);
	asset->add("/data/room/30.room", room);
	asset->add("/data/room/31.room", room);
	asset->add("/data/room/32.room", room);
	asset->add("/data/room/33.room", room);
	asset->add("/data/room/34.room", room);
	asset->add("/data/room/35.room", room);
	asset->add("/data/room/36.room", room);
	asset->add("/data/room/37.room", room);
	asset->add("/data/room/38.room", room);
	asset->add("/data/room/39.room", room);
	asset->add("/data/room/40.room", room);
	asset->add("/data/room/41.room", room);
	asset->add("/data/room/42.room", room);
	asset->add("/data/room/43.room", room);
	asset->add("/data/room/44.room", room);
	asset->add("/data/room/45.room", room);
	asset->add("/data/room/46.room", room);
	asset->add("/data/room/47.room", room);
	asset->add("/data/room/48.room", room);
	asset->add("/data/room/49.room", room);
	asset->add("/data/room/50.room", room);
	asset->add("/data/room/51.room", room);
	asset->add("/data/room/52.room", room);
	asset->add("/data/room/53.room", room);
	asset->add("/data/room/54.room", room);
	asset->add("/data/room/55.room", room);
	asset->add("/data/room/56.room", room);
	asset->add("/data/room/57.room", room);
	asset->add("/data/room/58.room", room);
	asset->add("/data/room/59.room", room);
	asset->add("/data/room/60.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("/data/room/07.tmx", room);
	asset->add("/data/room/08.tmx", room);
	asset->add("/data/room/09.tmx", room);
	asset->add("/data/room/10.tmx", room);
	asset->add("/data/room/11.tmx", room);
	asset->add("/data/room/12.tmx", room);
	asset->add("/data/room/13.tmx", room);
	asset->add("/data/room/14.tmx", room);
	asset->add("/data/room/15.tmx", room);
	asset->add("/data/room/16.tmx", room);
	asset->add("/data/room/17.tmx", room);
	asset->add("/data/room/18.tmx", room);
	asset->add("/data/room/19.tmx", room);
	asset->add("/data/room/20.tmx", room);
	asset->add("/data/room/21.tmx", room);
	asset->add("/data/room/22.tmx", room);
	asset->add("/data/room/23.tmx", room);
	asset->add("/data/room/24.tmx", room);
	asset->add("/data/room/25.tmx", room);
	asset->add("/data/room/26.tmx", room);
	asset->add("/data/room/27.tmx", room);
	asset->add("/data/room/28.tmx", room);
	asset->add("/data/room/29.tmx", room);
	asset->add("/data/room/30.tmx", room);
	asset->add("/data/room/31.tmx", room);
	asset->add("/data/room/32.tmx", room);
	asset->add("/data/room/33.tmx", room);
	asset->add("/data/room/34.tmx", room);
	asset->add("/data/room/35.tmx", room);
	asset->add("/data/room/36.tmx", room);
	asset->add("/data/room/37.tmx", room);
	asset->add("/data/room/38.tmx", room);
	asset->add("/data/room/39.tmx", room);
	asset->add("/data/room/40.tmx", room);
	asset->add("/data/room/41.tmx", room);
	asset->add("/data/room/42.tmx", room);
	asset->add("/data/room/43.tmx", room);
	asset->add("/data/room/44.tmx", room);
	asset->add("/data/room/45.tmx", room);
	asset->add("/data/room/46.tmx", room);
	asset->add("/data/room/47.tmx", room);
	asset->add("/data/room/48.tmx", room);
	asset->add("/data/room/49.tmx", room);
	asset->add("/data/room/50.tmx", room);
	asset->add("/data/room/51.tmx", room);
	asset->add("/data/room/52.tmx", room);
	asset->add("/data/room/53.tmx", room);
	asset->add("/data/room/54.tmx", room);
	asset->add("/data/room/55.tmx", room);
	asset->add("/data/room/56.tmx", room);
	asset->add("/data/room/57.tmx", room);
	asset->add("/data/room/58.tmx", room);
	asset->add("/data/room/59.tmx", room);
	asset->add("/data/room/60.tmx", room);

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

	asset->add("/data/enemies/paco.png", bitmap);
	asset->add("/data/enemies/paco.ani", data);
	asset->add("/data/enemies/chip.png", bitmap);
	asset->add("/data/enemies/chip.ani", data);
	asset->add("/data/enemies/wave.png", bitmap);
	asset->add("/data/enemies/wave.ani", data);
	asset->add("/data/enemies/wave_v.png", bitmap);
	asset->add("/data/enemies/wave_v.ani", data);
	asset->add("/data/enemies/sigmasua.png", bitmap);
	asset->add("/data/enemies/sigmasua.ani", data);
	asset->add("/data/enemies/diskette.png", bitmap);
	asset->add("/data/enemies/diskette.ani", data);
	asset->add("/data/enemies/bird.png", bitmap);
	asset->add("/data/enemies/bird.ani", data);
	asset->add("/data/enemies/bin.png", bitmap);
	asset->add("/data/enemies/bin.ani", data);
	asset->add("/data/enemies/qvoid.png", bitmap);
	asset->add("/data/enemies/qvoid.ani", data);
	asset->add("/data/enemies/batman.png", bitmap);
	asset->add("/data/enemies/batman.ani", data);
	asset->add("/data/enemies/tuno.png", bitmap);
	asset->add("/data/enemies/tuno.ani", data);
	asset->add("/data/enemies/matatunos.png", bitmap);
	asset->add("/data/enemies/matatunos.ani", data);
	asset->add("/data/enemies/abad.png", bitmap);
	asset->add("/data/enemies/abad.ani", data);
	asset->add("/data/enemies/jailbattle_human.png", bitmap);
	asset->add("/data/enemies/jailbattle_human.ani", data);
	asset->add("/data/enemies/jailbattle_alien.png", bitmap);
	asset->add("/data/enemies/jailbattle_alien.ani", data);
	asset->add("/data/enemies/jailer.png", bitmap);
	asset->add("/data/enemies/jailer.ani", data);
	asset->add("/data/enemies/jailer2.png", bitmap);
	asset->add("/data/enemies/jailer2.ani", data);
	asset->add("/data/enemies/jailer3.png", bitmap);
	asset->add("/data/enemies/jailer3.ani", data);
	asset->add("/data/enemies/printer.png", bitmap);
	asset->add("/data/enemies/printer.ani", data);

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

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

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

	asset->add("/data/sound/item.wav", sound);
	asset->add("/data/sound/death.wav", sound);
	asset->add("/data/sound/jump1.wav", sound);
	asset->add("/data/sound/jump2.wav", sound);
	asset->add("/data/sound/jump3.wav", sound);
	asset->add("/data/sound/jump4.wav", sound);
	asset->add("/data/sound/jump5.wav", sound);
	asset->add("/data/sound/jump6.wav", sound);
	asset->add("/data/sound/jump7.wav", sound);
	asset->add("/data/sound/jump8.wav", sound);
	asset->add("/data/sound/jump9.wav", sound);
	asset->add("/data/sound/jump10.wav", sound);
	asset->add("/data/sound/jump11.wav", sound);
	asset->add("/data/sound/jump12.wav", sound);
	asset->add("/data/sound/jump13.wav", sound);
	asset->add("/data/sound/jump14.wav", sound);
	asset->add("/data/sound/jump15.wav", sound);
	asset->add("/data/sound/jump16.wav", sound);
	asset->add("/data/sound/jump17.wav", sound);
	asset->add("/data/sound/jump18.wav", sound);
	asset->add("/data/sound/jump19.wav", sound);
	asset->add("/data/sound/jump20.wav", sound);
	asset->add("/data/sound/jump21.wav", sound);
	asset->add("/data/sound/jump22.wav", sound);
	asset->add("/data/sound/jump23.wav", sound);
	asset->add("/data/sound/jump24.wav", sound);

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

	asset->add("/data/title/loading_screen1.png", bitmap);
	asset->add("/data/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 los creditos del juego
void Director::runCredits()
{
	credits = new Credits(renderer, screen, asset);
	setSection(credits->run());
	delete credits;
}

// 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_CREDITS:
			runCredits();
			break;
		case SECTION_PROG_GAME:
			runGame();
			break;
		}
	}
}