#include "InvControls.h"
#include "InvParams.h"
#include <list>

//New keys down on this frame
static std::list<SDL_keysym> newKeysDown;
static std::list<Uint8> newButtonsDown;

//New keys up on this frame
static std::list<SDL_keysym> newKeysUp;
static std::list<Uint8> newButtonsUp;

//Keys held down
static std::list<SDL_keysym> keysDown;
static std::list<Uint8> buttonsDown;

//Mouse position
static int mousemovex;
static int mousemovey;
static int mousex;
static int mousey;

//Lock mouse for mlook controls
static bool lockMouse = false;;


//Feed an event into the controls system
void _controls_handleEvent(SDL_Event* e)
{
	switch (e->type)
	{
	case SDL_KEYDOWN:
		newKeysDown.push_back(e->key.keysym);
		keysDown.push_back(e->key.keysym);
		break;
	case SDL_KEYUP:
		newKeysUp.push_back(e->key.keysym);

		//Remove from down list
		for (auto it = keysDown.begin(); it != keysDown.end(); it++)
			if ((*it).scancode == e->key.keysym.scancode)
			{
				keysDown.erase(it);
				break;
			}
		break;

	case SDL_MOUSEMOTION:
		mousemovex = e->motion.xrel;
		mousemovey = e->motion.yrel;
		mousex = e->motion.x;
		mousey = e->motion.y;
		if (lockMouse) SDL_WarpMouse(200,200);
		break;

	case SDL_MOUSEBUTTONDOWN:
		newButtonsDown.push_back(e->button.button);
		buttonsDown.push_back(e->button.button);
		break;
	case SDL_MOUSEBUTTONUP:
		newButtonsUp.push_back(e->button.button);

		//Remove from down list
		for (auto it = buttonsDown.begin(); it != buttonsDown.end(); it++)
			if ((*it) == e->button.button)
			{
				buttonsDown.erase(it);
				break;
			}
		break;
	}
}


//New frame, flip controls
void _controls_step()
{
	newKeysDown.clear();
	newKeysUp.clear();
	newButtonsDown.clear();
	newButtonsUp.clear();
	mousemovex = 0;
	mousemovey = 0;
}



bool keyPressed(SDLKey key)
{
	for (auto it = newKeysDown.begin(); it != newKeysDown.end(); it++)
		if ((*it).sym == key) return true;
	return false;
}

bool keyDown(SDLKey key)
{
	for (auto it = keysDown.begin(); it != keysDown.end(); it++)
		if ((*it).sym == key) return true;
	return false;
}

bool keyReleased(SDLKey key)
{
	for (auto it = newKeysUp.begin(); it != newKeysUp.end(); it++)
		if ((*it).sym == key) return true;
	return false;
}

bool keyUp(SDLKey key)
{
	return !keyDown(key);
}

bool mousePressed(Uint8 button)
{
	for (auto it = newButtonsDown.begin(); it != newButtonsDown.end(); it++)
		if ((*it) == button) return true;
	return false;
}

bool mouseDown(Uint8 button)
{
	for (auto it = buttonsDown.begin(); it != buttonsDown.end(); it++)
		if ((*it) == button) return true;
	return false;
}

bool mouseReleased(Uint8 button)
{
	for (auto it = newButtonsUp.begin(); it != newButtonsUp.end(); it++)
		if ((*it) == button) return true;
	return false;
}

bool mouseUp(Uint8 button)
{
	return !mouseDown(button);
}


int mouseX()
{
	return mousex;
}

int mouseY()
{
	return mousey;
}

int mouseMoveX()
{
	return mousemovex;
}

int mouseMoveY()
{
	return mousemovey;
}