#include <akgltest.h>

akerr_ErrorContext AKERR_NOIGNORE *savegame(akgl_Actor *obj, SDL_Event *event)
{
    return akgl_game_save("assets/savegame.bin");
}

akerr_ErrorContext AKERR_NOIGNORE *quit_game(akgl_Actor *obj, SDL_Event *event)
{
    PREPARE_ERROR(e);
    AKGL_BITMASK_ADD(game.state.flags, AKGLTEST_STATE_QUIT);
    SDL_Log("Quitting game");
    SUCCEED_RETURN(e);
}

SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event)
{
    PREPARE_ERROR(e);
    
    ATTEMPT {
	CATCH(e, akgl_game_state_lock());
	FAIL_ZERO_BREAK(e, appstate, AKERR_NULLPOINTER, "NULL appstate pointer");
	FAIL_ZERO_BREAK(e, event, AKERR_NULLPOINTER, "NULL event pointer");
	
	if ( AKGL_BITMASK_HAS(game.state.flags, AKGLTEST_STATE_WAITFORINPUT) ) {
	    if ( event->type == SDL_EVENT_GAMEPAD_BUTTON_DOWN ||
		 event->type == SDL_EVENT_GAMEPAD_BUTTON_UP ||
		 event->type == SDL_EVENT_KEY_DOWN ||
		 event->type == SDL_EVENT_KEY_UP ) {
		// get the player's default keyboard or gamepad id from the event
		CATCH(e, akgltest_controller_get_defaults(appstate, event));
		CATCH(e, akgltest_set_gamemode_menu(appstate, event));
	    }
	} else {
	    CATCH(e, akgl_controller_handle_event(appstate, event));
	}
	if (event->type == SDL_EVENT_QUIT) {
	    return SDL_APP_SUCCESS;  /* end the program, reporting success to the OS. */
	}
    } CLEANUP {
	IGNORE(akgl_game_state_unlock());
    } PROCESS(e) {
    } FINISH_NORETURN(e);
    return SDL_APP_CONTINUE;  /* carry on with the program! */
}
