#include "main.h"
#include "input.h"
#include "gfx.h"

const char *btn_names[BTN_MAX] = {
	"UP","DOWN","LEFT","RIGHT","JUMP","SHOOT",
	"PREVWEAPON","NEXTWEAPON","ITEMS","MAP",
	"CHECK","OK","QUIT","CHAT","LOG","SCORE"
};
Uint16 btn_start,btn_end,buttons;
Uint8 button_time[BTN_MAX];

typedef struct {
	SDLKey key;
	Uint8 btn;
} Keymap;
Keymap *keymap = NULL;
Uint16 keymap_size = 0;

void I_SetKeymap(SDLKey key, Uint8 button)
{
	/*Uint16 i;
	for (i = 0; i < keymap_size; i++)
	{
		if (keymap[i].key == key) {
			keymap[i].btn = button;
			return;
		}
	}*/
	keymap_size++;
	keymap = realloc(keymap,keymap_size*sizeof(Keymap));
	keymap[keymap_size-1] = (Keymap){key,button};
}

bool I_HandleEvent(SDL_Event ev)
{
	switch(ev.type) {
	case SDL_QUIT:
		return true;
	case SDL_KEYDOWN:
		{
			SDLKey key = ev.key.keysym.sym;
			Uint16 i;
			for (i = 0; i < keymap_size; i++)
				if (key == keymap[i].key) {
					btn_start |= 1<<keymap[i].btn;
					buttons |= 1<<keymap[i].btn;
					//break;
				}
			if (key == SDLK_ESCAPE)
				return true;
		}
		break;
	case SDL_KEYUP:
		{
			SDLKey key = ev.key.keysym.sym;
			Uint16 i;
			for (i = 0; i < keymap_size; i++)
				if (key == keymap[i].key) {
					btn_end |= 1<<keymap[i].btn;
					buttons &= ~(1<<keymap[i].btn);
					//break;
				}
		}
		break;
	case SDL_ACTIVEEVENT:
		if (!(gfx_flags & GFX_FULLSCREEN))
			break;
		if (!ev.active.gain) {
			gfx_flags &= ~GFX_CANDRAW;
			break;
		}
	case SDL_VIDEOEXPOSE:
		{
			// REDRAW ALL VIDEO SURFACES
			gfx_flags |= GFX_CANDRAW;
		}
		break;
	default:
		break;
	}
	return false;
}
