#include <GL/glfw.h>
#include "Input.h"
#include "Global_Properties.h"

namespace Input
{

	// Singleton implimentation
	InputManager* InputManager::sInstance = 0;
	InputManager& InputManager::I()
	{
		if (sInstance == 0)
			sInstance = new InputManager();

		return *sInstance;
	}

	InputManager::InputManager(): mResetMousePos(true)
	{
		// Init mouse
		CenterMousePos();
		ShowMouseCursor(GlobalProperties::SHOW_MOUSE_CURSOR);
		glfwGetMousePos(&mMouseX, &mMouseY);
		mMouseLastX = mMouseX;
		mMouseLastY = mMouseY;

		mMouseEnabled = GlobalProperties::ALLOW_MOUSE_INPUT;
		mKeyboardEnabled = GlobalProperties::ALLOW_KEYBOARD_INPUT;
		mMouseSpeedH = GlobalProperties::MOUSE_H_SPEED;
		mMouseSpeedV = GlobalProperties::MOUSE_V_SPEED;

		INIT_INPUT_KEY(W, 'W');
		INIT_INPUT_KEY(A, 'A');
		INIT_INPUT_KEY(S, 'S');
		INIT_INPUT_KEY(D, 'D');
		INIT_INPUT_KEY(Shift, GLFW_KEY_LSHIFT);
		INIT_INPUT_KEY(Space, GLFW_KEY_SPACE);
		INIT_INPUT_KEY(LMouseButton, GLFW_MOUSE_BUTTON_LEFT);
	}

	void InputManager::UpdateMousePos(int aX, int aY)
	{
		mMouseLastX = mMouseX;
		mMouseLastY = mMouseY;
		mMouseX = aX;
		mMouseY = aY;

		if (mResetMousePos)
			CenterMousePos();
	}

	void InputManager::UpdateMouseButtons()
	{
		UPDATE_MOUSE_BUTTON(LMouseButton);
	}

	void InputManager::UpdateKeyboardButtons()
	{
		UPDATE_KEYBOARD_BUTTON(W);
		UPDATE_KEYBOARD_BUTTON(A);
		UPDATE_KEYBOARD_BUTTON(S);
		UPDATE_KEYBOARD_BUTTON(D);
		UPDATE_KEYBOARD_BUTTON(Shift);
		UPDATE_KEYBOARD_BUTTON(Space);
	}

	bool InputManager::IsEnabled(InputType aType)
	{
		bool flag = mMouseEnabled;

		if (aType == INPUT_TYPE_KEYBOARD)
			flag = mKeyboardEnabled;
		// else joypad?

		return flag;
	}

	void InputManager::SetEnabled(InputType aType, bool aState)
	{
		if (aType == INPUT_TYPE_MOUSE)
			mMouseEnabled = aState;
		else if (aType == INPUT_TYPE_KEYBOARD)
			mKeyboardEnabled = aState;
	}

	void InputManager::CenterMousePos()
	{
		glfwSetMousePos(GlobalProperties::SCREEN_WIDTH_HALF, GlobalProperties::SCREEN_HEIGHT_HALF);
	}

	void InputManager::ShowMouseCursor(bool aShow)
	{
		if (aShow)
			glfwEnable(GLFW_MOUSE_CURSOR);
		else
			glfwDisable(GLFW_MOUSE_CURSOR);
	}

}