#include "input.h"
#include <SDL2/SDL.h>		   // para SDL_INIT_GAMECONTROLLER, SDL_InitSubS...
#include <SDL2/SDL_error.h>	   // para SDL_GetError
#include <SDL2/SDL_events.h>   // para SDL_ENABLE
#include <SDL2/SDL_keyboard.h> // para SDL_GetKeyboardState
#include <iostream>			   // para basic_ostream, operator<<, cout, basi...
#include <unordered_map>
#include <algorithm>

// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
Input *Input::input_ = nullptr;

// [SINGLETON] Crearemos el objeto input con esta función estática
void Input::init(const std::string &game_controller_db_path)
{
	Input::input_ = new Input(game_controller_db_path);
}

// [SINGLETON] Destruiremos el objeto input con esta función estática
void Input::destroy()
{
	delete Input::input_;
}

// [SINGLETON] Con este método obtenemos el objeto input y podemos trabajar con él
Input *Input::get()
{
	return Input::input_;
}

// Constructor
Input::Input(const std::string &game_controller_db_path)
	: game_controller_db_path_(game_controller_db_path)
{
	// Busca si hay mandos conectados
	discoverGameControllers();

	// Inicializa los vectores
	key_bindings_.resize(static_cast<int>(InputType::NUMBER_OF_INPUTS), KeyBindings());
	controller_bindings_.resize(num_gamepads_, std::vector<ControllerBindings>(static_cast<int>(InputType::NUMBER_OF_INPUTS), ControllerBindings()));

	// Listado de los inputs para jugar que utilizan botones, ni palancas ni crucetas
	button_inputs_ = {InputType::FIRE_LEFT, InputType::FIRE_CENTER, InputType::FIRE_RIGHT, InputType::START};
}

// Asigna inputs a teclas
void Input::bindKey(InputType input, SDL_Scancode code)
{
	key_bindings_.at(static_cast<int>(input)).scancode = code;
}

// Asigna inputs a botones del mando
void Input::bindGameControllerButton(int controller_index, InputType input, SDL_GameControllerButton button)
{
	if (controller_index < num_gamepads_)
	{
		controller_bindings_.at(controller_index).at(static_cast<int>(input)).button = button;
	}
}

// Asigna inputs a botones del mando
void Input::bindGameControllerButton(int controller_index, InputType input_target, InputType input_source)
{
	if (controller_index < num_gamepads_)
	{
		controller_bindings_.at(controller_index).at(static_cast<int>(input_target)).button = controller_bindings_.at(controller_index).at(static_cast<int>(input_source)).button;
	}
}

// Comprueba si un input esta activo
bool Input::checkInput(InputType input, bool repeat, InputDeviceToUse device, int controller_index)
{
	bool success_keyboard = false;
	bool success_controller = false;
	const int input_index = static_cast<int>(input);

	if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY)
	{
		const Uint8 *keyStates = SDL_GetKeyboardState(nullptr);

		if (repeat)
		{
			if (keyStates[key_bindings_[input_index].scancode] != 0)
			{
				success_keyboard = true;
			}
			else
			{
				success_keyboard = false;
			}
		}
		else
		{
			if (!key_bindings_[input_index].active)
			{
				if (keyStates[key_bindings_[input_index].scancode] != 0)
				{
					key_bindings_[input_index].active = true;
					success_keyboard = true;
				}
				else
				{
					success_keyboard = false;
				}
			}
			else
			{
				if (keyStates[key_bindings_[input_index].scancode] == 0)
				{
					key_bindings_[input_index].active = false;
					success_keyboard = false;
				}
				else
				{
					success_keyboard = false;
				}
			}
		}
	}

	if (gameControllerFound() && controller_index >= 0 && controller_index < num_gamepads_)
		if ((device == InputDeviceToUse::CONTROLLER) || (device == InputDeviceToUse::ANY))
		{
			success_controller = checkAxisInput(input, controller_index);
			if (!success_controller)
			{
				if (repeat)
				{
					if (SDL_GameControllerGetButton(connected_controllers_[controller_index], controller_bindings_[controller_index][input_index].button) != 0)
					{
						success_controller = true;
					}
					else
					{
						success_controller = false;
					}
				}
				else
				{
					if (!controller_bindings_[controller_index][input_index].active)
					{
						if (SDL_GameControllerGetButton(connected_controllers_[controller_index], controller_bindings_[controller_index][input_index].button) != 0)
						{
							controller_bindings_[controller_index][input_index].active = true;
							success_controller = true;
						}
						else
						{
							success_controller = false;
						}
					}
					else
					{
						if (SDL_GameControllerGetButton(connected_controllers_[controller_index], controller_bindings_[controller_index][input_index].button) == 0)
						{
							controller_bindings_[controller_index][input_index].active = false;
							success_controller = false;
						}
						else
						{
							success_controller = false;
						}
					}
				}
			}
		}

	return (success_keyboard || success_controller);
}

// Comprueba si hay almenos un input activo
bool Input::checkAnyInput(InputDeviceToUse device, int controller_index)
{
	if (device == InputDeviceToUse::ANY)
	{
		controller_index = 0;
	}

	if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY)
	{
		const Uint8 *mKeystates = SDL_GetKeyboardState(nullptr);

		for (int i = 0; i < (int)key_bindings_.size(); ++i)
		{
			if (mKeystates[key_bindings_[i].scancode] != 0 && !key_bindings_[i].active)
			{
				key_bindings_[i].active = true;
				return true;
			}
		}
	}

	if (gameControllerFound())
	{
		if (device == InputDeviceToUse::CONTROLLER || device == InputDeviceToUse::ANY)
		{
			for (int i = 0; i < (int)controller_bindings_.size(); ++i)
			{
				if (SDL_GameControllerGetButton(connected_controllers_[controller_index], controller_bindings_[controller_index][i].button) != 0 && !controller_bindings_[controller_index][i].active)
				{
					controller_bindings_[controller_index][i].active = true;
					return true;
				}
			}
		}
	}

	return false;
}

// Comprueba si hay algún botón pulsado. Devuelve 0 en caso de no encontrar nada o el indice del dispositivo + 1. Se hace así para poder gastar el valor devuelto como un valor "booleano"
int Input::checkAnyButtonPressed(bool repeat)
{
	// Si está pulsado el botón de servicio, ningún botón se puede considerar pulsado
	if (checkInput(InputType::SERVICE, INPUT_ALLOW_REPEAT, InputDeviceToUse::ANY))
	{
		return 0;
	}

	// Solo comprueba los botones definidos previamente
	for (auto bi : button_inputs_)
	{
		// Comprueba el teclado
		if (checkInput(bi, repeat, InputDeviceToUse::KEYBOARD))
		{
			return 1;
		}

		// Comprueba los mandos
		for (int i = 0; i < num_gamepads_; ++i)
		{
			if (checkInput(bi, repeat, InputDeviceToUse::CONTROLLER, i))
			{
				return i + 1;
			}
		}
	}

	return 0;
}

// Busca si hay mandos conectados
bool Input::discoverGameControllers()
{
	bool found = false;

	if (SDL_WasInit(SDL_INIT_GAMECONTROLLER) != 1)
	{
		SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER);
	}

	if (SDL_GameControllerAddMappingsFromFile(game_controller_db_path_.c_str()) < 0)
	{
		std::cout << "Error, could not load " << game_controller_db_path_.c_str() << " file: " << SDL_GetError() << std::endl;
	}

	num_joysticks_ = SDL_NumJoysticks();
	num_gamepads_ = 0;

	// Cuenta el número de mandos
	joysticks_.clear();
	for (int i = 0; i < num_joysticks_; ++i)
	{
		auto joy = SDL_JoystickOpen(i);
		joysticks_.push_back(joy);
		if (SDL_IsGameController(i))
		{
			num_gamepads_++;
		}
	}

	std::cout << "\n** LOOKING FOR GAME CONTROLLERS" << std::endl;
	std::cout << "Gamepads found: " << num_gamepads_ << std::endl;

	if (num_gamepads_ > 0)
	{
		found = true;

		for (int i = 0; i < num_gamepads_; i++)
		{
			// Abre el mando y lo añade a la lista
			auto pad = SDL_GameControllerOpen(i);
			if (SDL_GameControllerGetAttached(pad) == 1)
			{
				connected_controllers_.push_back(pad);
				const std::string name = SDL_GameControllerNameForIndex(i);
				std::cout << "#" << i << ": " << name << std::endl;
				controller_names_.push_back(name);
			}
			else
			{
				std::cout << "SDL_GetError() = " << SDL_GetError() << std::endl;
			}
		}

		SDL_GameControllerEventState(SDL_ENABLE);
	}

	std::cout << "\n** FINISHED LOOKING FOR GAME CONTROLLERS" << std::endl;
	return found;
}

// Comprueba si hay algun mando conectado
bool Input::gameControllerFound() { return num_gamepads_ > 0 ? true : false; }

// Obten el nombre de un mando de juego
std::string Input::getControllerName(int controller_index) const { return num_gamepads_ > 0 ? controller_names_.at(controller_index) : std::string(); }

// Obten el número de mandos conectados
int Input::getNumControllers() const { return num_gamepads_; }

// Obtiene el indice del controlador a partir de un event.id
int Input::getJoyIndex(int id) const
{
	for (int i = 0; i < num_joysticks_; ++i)
	{
		if (SDL_JoystickInstanceID(joysticks_[i]) == id)
		{
			return i;
		}
	}
	return -1;
}

// Muestra por consola los controles asignados
void Input::printBindings(InputDeviceToUse device, int controller_index) const
{
	if (device == InputDeviceToUse::ANY || device == InputDeviceToUse::KEYBOARD)
	{
		return;
	}

	if (device == InputDeviceToUse::CONTROLLER)
	{
		if (controller_index >= num_gamepads_)
		{
			return;
		}

		// Muestra el nombre del mando
		std::cout << "\n" + controller_names_.at(controller_index) << std::endl;

		// Muestra los botones asignados
		for (auto bi : button_inputs_)
		{
			std::cout << to_string(bi) << " : " << controller_bindings_.at(controller_index).at(static_cast<int>(bi)).button << std::endl;
		}
	}
}

// Obtiene el SDL_GameControllerButton asignado a un input
SDL_GameControllerButton Input::getControllerBinding(int controller_index, InputType input) const
{
	return controller_bindings_[controller_index][static_cast<int>(input)].button;
}

// Obtiene el indice a partir del nombre del mando
int Input::getIndexByName(const std::string &name) const
{
	auto it = std::find(controller_names_.begin(), controller_names_.end(), name);
	return it != controller_names_.end() ? std::distance(controller_names_.begin(), it) : -1;
}

// Convierte un InputType a std::string
std::string Input::to_string(InputType input) const
{
	switch (input)
	{
	case InputType::FIRE_LEFT:
		return "input_fire_left";
	case InputType::FIRE_CENTER:
		return "input_fire_center";
	case InputType::FIRE_RIGHT:
		return "input_fire_right";
	case InputType::START:
		return "input_start";
	case InputType::SERVICE:
		return "input_service";
	default:
		return "";
	}
}

// Convierte un std::string a InputType
InputType Input::to_inputs_e(const std::string &name) const
{
	static const std::unordered_map<std::string, InputType> inputMap = {
		{"input_fire_left", InputType::FIRE_LEFT},
		{"input_fire_center", InputType::FIRE_CENTER},
		{"input_fire_right", InputType::FIRE_RIGHT},
		{"input_start", InputType::START},
		{"input_service", InputType::SERVICE}};

	auto it = inputMap.find(name);
	return it != inputMap.end() ? it->second : InputType::NONE;
}

// Comprueba el eje del mando
bool Input::checkAxisInput(InputType input, int controller_index) const
{
	switch (input)
	{
	case InputType::LEFT:
		return SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTX) < -30000;
	case InputType::RIGHT:
		return SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTX) > 30000;
	case InputType::UP:
		return SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTY) < -30000;
	case InputType::DOWN:
		return SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTY) > 30000;
	default:
		return false;
	}
}

// Establece el indice de mando que usará el teclado
void Input::setKeyboardIndex(int index)
{
	keyboard_index_ = index;
}