#include "input.h"

namespace ngObjects
{
	Input::Input(int w, int h, int fov, int rotLim)
	{
		// Set window width, height, and dots per pixel
		windowW = w;
		windowH = h;
		vdpp = fov / (float)h;
		hdpp = fov / (float)w;
		rotationLimit = rotLim;
	}
	int Input::keyDown(SDL_keysym *keysym)
	{
		// Switch to handle various key presses
		switch( keysym->sym ) 
		{
			case SDLK_ESCAPE:
				return 0;

			default:
				return 1;
		}
	}
	int Input::keyUp(SDL_keysym *keysym)
	{
		// Switch to handle various key releases
		switch( keysym->sym ) 
		{
			default:
				return 1;
		}
	}
	void Input::mouseButton(SDL_MouseButtonEvent *mouse)
	{
		if (mouse->type == SDL_MOUSEBUTTONDOWN)
		{
			// Hide cursor, grab input, center and lock mouse
			//SDL_ShowCursor(SDL_DISABLE);
			SDL_WM_GrabInput(SDL_GRAB_ON);
			int x,y;
			SDL_GetMouseState(&x, &y);
			mouseLockX = x;
			mouseLockY = y;
			mouseDown = true;
		}
		else
		{
			// Show cursor, release input, and let caller know mouse is not being used
			//SDL_ShowCursor(SDL_ENABLE);
			SDL_WM_GrabInput(SDL_GRAB_OFF);
			SDL_WarpMouse(mouseLockX, mouseLockY);
			mouseDown = false;
		}
	}
	int Input::mouseMotion(GLfloat *rotX, GLfloat *rotY)
	{
		if (mouseDown)
		{
			int moveLenX, moveLenY;

			// Get current mouse values then warp mouse to lock point
			SDL_GetMouseState(&mouseX, &mouseY);
			SDL_WarpMouse(mouseLockX, mouseLockY);

			// mouse postion is in start.. mouse out of program window bug fix
			if (mouseX == 0 && mouseY == 0)
				return 1;
			// The mouse did not move.. dont update (must be X & Y or it does the jitter)
			if (mouseX == mouseLockX && mouseY == mouseLockY)
				return 1;

			moveLenX = mouseLockX - mouseX;
			moveLenY = mouseLockY - mouseY;

			// To fix the bug where you can break limits by moving mouse fast enough
			// put some code in here to determine if the length the mouse moved is to far
			
			// Limit roation around X axis to +-rotationLimit.. This could be done better
			//if (*rotX > rotationLimit && moveLenY > 0)
			//{}
			//else if (*rotX < -rotationLimit && moveLenY < 0)
			//{}
			//else
				*rotX += vdpp * moveLenY; // Calulate X rotation angle
			// Calulate Y rotation angle
			*rotY += hdpp * moveLenX;

			// It's generally not a good idea to use angles larger then 360
			if (*rotY >= 360.0)
				*rotY -= 360;
			if (*rotY <= -360.0)
				*rotY += 360;
			// It's generally not a good idea to use angles larger then 360
			if (*rotX >= 360.0)
				*rotX -= 360;
			if (*rotX <= -360.0)
				*rotX += 360;

			return 1;
		}
		else
			return 0;
	}
}
