#include <akgltest.h>

SDL_AppResult SDL_AppInit(void **appstate, int argc, char *argv[])
{
    akgl_Actor *actorptr = NULL;
    *appstate = (void *)&game.state;
    PREPARE_ERROR(e);
    
    AKGL_BITMASK_ADD(game.state.flags, AKGLTEST_STATE_LOADING);
    
    ATTEMPT {
	FAIL_ZERO_BREAK(e, appstate, AKERR_NULLPOINTER, "NULL appstate pointer");

	strcpy((char *)&game.name, "sdl3-gametest");
	strcpy((char *)&game.version, "0.0.1");
	strcpy((char *)&game.uri, "net.aklabs.games.sdl3-gametest");

	//CATCH(e, akgl_game_load("assets/savegame.bin"));
	CATCH(e, akgl_game_init());
	CATCH(e, akgl_game_state_lock());
	CATCH(e, akgl_registry_load_properties("assets/properties.json"));
	CATCH(e, akgl_render_init2d(renderer));
	CATCH(e, akgl_physics_init_arcade(physics));
	CATCH(e, akgl_controller_list_keyboards());
	
	CATCH(e, akgltest_load_assets());
		
	CATCH(e, akgl_heap_next_actor(&actorptr));
	CATCH(e, akgl_actor_initialize((akgl_Actor *)actorptr, "player"));
	actorptr->basechar = SDL_GetPointerProperty(
	    AKGL_REGISTRY_CHARACTER,
	    "little guy",
	    NULL);
	FAIL_ZERO_BREAK(e, actorptr->basechar, AKGL_ERR_REGISTRY, "Can't load character 'little guy' from the registry");
	actorptr->movement_controls_face = false;
	actorptr->state = (AKGL_ACTOR_STATE_ALIVE | AKGL_ACTOR_STATE_FACE_LEFT);
	actorptr->x = 320;
	actorptr->y = 240;
	actorptr->visible = false;

	strcpy((char *)&dirnamebuf, "assets/memories.mp3");
	CATCH(e, akgl_load_start_bgm((char *)&dirnamebuf));
	CATCH(e, music_toggle(NULL, NULL));
	
	CATCH(e, akgl_text_loadfont("C64Pro", "assets/C64_Pro-STYLE.ttf", 18));

	
    } CLEANUP {
	IGNORE(akgl_game_state_unlock());
    } PROCESS(e) {
    } HANDLE_DEFAULT(e) {
	LOG_ERROR(e);
	return SDL_APP_FAILURE;
    } FINISH_NORETURN(e);
      
    AKGL_BITMASK_DEL(game.state.flags, AKGLTEST_STATE_LOADING);
    AKGL_BITMASK_ADD(game.state.flags, AKGLTEST_STATE_WAITFORINPUT);

    return SDL_APP_CONTINUE;
}
