#include "director.h"

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

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

// Inicializa JailAudio
void Director::initJailAudio()
{
	JA_Init(44100, 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
		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;
}

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

// Crea el indice de ficheros de recursos
bool Director::setFileList()
{
	// Ficheros del mapa
	asset->add("/data/map/01.map", data);
	asset->add("/data/map/01.tmx", data);
	asset->add("/data/map/01.ene", data);
	asset->add("/data/map/02.map", data);
	asset->add("/data/map/02.tmx", data);
	asset->add("/data/map/02.ene", data);
	asset->add("/data/map/03.map", data);
	asset->add("/data/map/03.tmx", data);
	asset->add("/data/map/03.ene", data);
	asset->add("/data/map/04.map", data);
	asset->add("/data/map/04.tmx", data);
	asset->add("/data/map/05.map", data);
	asset->add("/data/map/05.tmx", data);
	asset->add("/data/map/06.map", data);
	asset->add("/data/map/06.tmx", data);
	asset->add("/data/map/07.map", data);
	asset->add("/data/map/07.tmx", data);
	asset->add("/data/map/08.map", data);
	asset->add("/data/map/08.tmx", data);
	asset->add("/data/map/09.map", data);
	asset->add("/data/map/09.tmx", data);
	asset->add("/data/map/10.map", data);
	asset->add("/data/map/10.tmx", data);
	asset->add("/data/map/tiles_surface.png", bitmap);

	// Ficheros de configuración
	asset->add("/data/config/config.txt", 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);
	asset->add("/data/sound/sound_menu_select.wav", sound);
	asset->add("/data/sound/sound_menu_cancel.wav", sound);
	asset->add("/data/sound/sound_menu_move.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);
	asset->add("/data/font/smb2.png", font);
	asset->add("/data/font/smb2.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);
	asset->add("/data/actors/enemies/manzana.png", bitmap);
	asset->add("/data/actors/enemies/manzana.ani", data);

	// Ficheros de actores
	asset->add("/data/actors/moving_platform.png", bitmap);
	asset->add("/data/actors/moving_platform.ani", data);
	asset->add("/data/actors/items/diamond.png", bitmap);
	asset->add("/data/actors/items/diamond.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);

	// Ficheros de menu
	asset->add("/data/menu/title.men", data);

	return asset->check();
}

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