#include <akgltest.h>

akerr_ErrorContext AKERR_NOIGNORE *akgltest_controller_bind_universal(char *actorname, int mapid, int kbid, int jsid)
{
    akgl_Control control;
    PREPARE_ERROR(e);
    
    PASS(e, akgl_controller_default(mapid, actorname, kbid, jsid));
    // set custom control maps */
    memset((void *)&control, 0x00, sizeof(akgl_Control));
    
    // Quit
    control.key = SDLK_ESCAPE;
    control.event_on = SDL_EVENT_KEY_DOWN;
    control.handler_on = &akgltest_set_gamemode_menu;
    PASS(e, akgl_controller_pushmap(mapid, &control));
    
    // Toggle the music
    control.key = SDLK_M;
    control.event_on = SDL_EVENT_KEY_DOWN;
    control.handler_on = &music_toggle;
    PASS(e, akgl_controller_pushmap(mapid, &control));

    // Save the game
    control.key = SDLK_S;
    control.event_on = SDL_EVENT_KEY_DOWN;
    control.handler_on = &savegame;
    PASS(e, akgl_controller_pushmap(AKGLTEST_CONTROLMAP_INGAMEACTOR, &control));

    // Menu selection
    control.key = SDLK_RETURN;
    control.event_on = SDL_EVENT_KEY_DOWN;
    control.handler_on = &akgltest_set_gamemode_running;
    PASS(e, akgl_controller_pushmap(AKGLTEST_CONTROLMAP_MENU, &control));

    if ( jsid != 0 ) {
	// Gamepad Menu selection. Use whatever button they pushed as the action
	control.button = SDL_GAMEPAD_BUTTON_START;
	control.event_on = SDL_EVENT_GAMEPAD_BUTTON_UP;
	control.handler_on = &akgltest_set_gamemode_running;
	PASS(e, akgl_controller_pushmap(AKGLTEST_CONTROLMAP_MENU, &control));

	// Toggle the music
	control.button = SDL_GAMEPAD_BUTTON_SOUTH;
	control.event_on = SDL_EVENT_GAMEPAD_BUTTON_UP;
	control.handler_on = &music_toggle;
	PASS(e, akgl_controller_pushmap(mapid, &control));
	
	// Quit
	control.button = SDL_GAMEPAD_BUTTON_EAST;
	control.event_on = SDL_EVENT_GAMEPAD_BUTTON_UP;
	control.handler_on = &akgltest_set_gamemode_menu;
	PASS(e, akgl_controller_pushmap(mapid, &control));
    }
    SUCCEED_RETURN(e);
}

akerr_ErrorContext AKERR_NOIGNORE *akgltest_controller_get_defaults(void *appstate, SDL_Event *event)
{
    akgl_Control control;

    PREPARE_ERROR(e);

    if (event->type == SDL_EVENT_GAMEPAD_BUTTON_DOWN || event->type == SDL_EVENT_GAMEPAD_BUTTON_UP) {
	jsid = event->gbutton.which;
    } else if (event->type == SDL_EVENT_KEY_DOWN || event->type == SDL_EVENT_KEY_UP) {
	kbid = event->key.which;
    }
        
    SUCCEED_RETURN(e);
}
