#include "input.h"


int mousewheelcode=WHEEL_OFF;
byte keys[256]={false};
extern POINT mousechange={0};
extern HWND hWnd;
extern ascreenmode screen_mode;
extern int anim_n;



int updateinput(void)
{
	int i=0;
	int vci=0;
	int fkey_wasdown[5]={keys[VK_F1],keys[VK_F2],keys[VK_F3],keys[VK_F4],keys[VK_F5]};
	int lmb_wasdown=keys[VK_LMB];
	int rmb_wasdown=keys[VK_RMB];

	while (i<256)
	{
		vci=vktochar(i);
		//if (!keys[vci])
		{
			if (vci!=VK_MOUSEWHEEL_DOWN && vci!=VK_MOUSEWHEEL_UP)
				keys[vci]=(GetAsyncKeyState(i) >> 8);
			else
				keys[vci]=((vci==VK_MOUSEWHEEL_DOWN && mousewheelcode==WHEEL_DOWN) || (vci==VK_MOUSEWHEEL_UP && mousewheelcode==WHEEL_UP));
		}
		i++;
	}

	
	if (keys[VK_LMB] || keys[VK_RMB])
	{
		POINT newpos;
		GetCursorPos(&newpos);
		ScreenToClient(hWnd,&newpos);

		if (newpos.x>=0 && newpos.x<=screen_mode.width)
			if (newpos.y>=0 && newpos.y<=screen_mode.height)
			{
				mousechange.x=newpos.x-(screen_mode.width/2);
				mousechange.y=newpos.y-(screen_mode.height/2);

				newpos.x=screen_mode.width/2;
				newpos.y=screen_mode.height/2;
				ClientToScreen(hWnd,&newpos);
				SetCursorPos(newpos.x,newpos.y);
			}

		if (!( (keys[VK_LMB]&&lmb_wasdown) || (keys[VK_RMB] && rmb_wasdown) ))
			mousechange.x=mousechange.y=0;

	} else {
		mousechange.x=mousechange.y=0;
	}

	if (!fkey_wasdown[0]&&keys[VK_F1])
		screen_mode.wireframe=!screen_mode.wireframe;

	if (!fkey_wasdown[1]&&keys[VK_F2])
		screen_mode.lighting=!screen_mode.lighting;

	if (!fkey_wasdown[2]&&keys[VK_F3])
		screen_mode.textureson=!screen_mode.textureson;

	if (!fkey_wasdown[3]&&keys[VK_F4])
		screen_mode.cartoonmode=!screen_mode.cartoonmode;

	if (!fkey_wasdown[4]&&keys[VK_F5])
		screen_mode.cell_shade=!screen_mode.cell_shade;



	return true;
}




int vktochar(int vk_code)
{

//	return vk_code;

	switch (vk_code){

	case VK_NUMPAD0:	return '0';
	case VK_NUMPAD1:	return '1';
	case VK_NUMPAD2:	return '2';
	case VK_NUMPAD3:	return '3';
	case VK_NUMPAD4:	return '4';
	case VK_NUMPAD5:	return '5';
	case VK_NUMPAD6:	return '6';
	case VK_NUMPAD7:	return '7';
	case VK_NUMPAD8:	return '8';
	case VK_NUMPAD9:	return '9';

	case VK_ADD:		return '+';
	case VK_SUBTRACT:	return '-';
	case VK_DECIMAL:	return '.';
	case VK_DIVIDE:		return '/';
	case VK_MULTIPLY:	return '*';

	case VK_SEMICOLON:	return ';';
	case VK_EQUALS:		return '=';
	case VK_COMMA:		return ',';
	case VK_MINUS:		return '-';
	case VK_PERIOD:		return '.';
	case VK_SLASH:		return '/';
	case VK_BACKQUOTE:	return '\'';
	case VK_LEFTBRACKET:return '[';
	case VK_BACKSLASH:	return '\\';
	case VK_RIGHTBRACKET:	return ']';
	case VK_HASH:		return '#';
	case VK_GRAVE:		return '`';

	}//switch
	
	return vk_code;
}