#define SDL_MAIN_USE_CALLBACKS
#include <SDL3/SDL.h>
#include <SDL3/SDL_main.h>
#include <SDL3/SDL_properties.h>
#include <SDL3_image/SDL_image.h>
#include <SDL3_mixer/SDL_mixer.h>

#include <akgl/assets.h>
#include <akgl/error.h>
#include <akgl/iterator.h>
#include <akgl/tilemap.h>
#include <akgl/heap.h>
#include <akgl/game.h>
#include <akgl/controller.h>
#include <akgl/draw.h>
#include <akgl/sprite.h>
#include <akgl/actor.h>
#include <akgl/registry.h>
#include <akgl/text.h>

#include <akstdlib.h>

#define AKGLTEST_STATE_WAITFORINPUT                   1 << 8
#define AKGLTEST_STATE_LOADING                        1 << 9
#define AKGLTEST_STATE_RUNNING                        1 << 10
#define AKGLTEST_STATE_MAPMENU                        1 << 11
#define AKGLTEST_STATE_QUIT                           1 << 12

#define AKGLTEST_CONTROLMAP_MENU                      0
#define AKGLTEST_CONTROLMAP_INGAMEACTOR               1

int menuselection = 0;
int maxmenu = 3;
int kbid = 0;
int jsid = 0;

int numchars = 2;
char *characterpaths[] = {
    "assets/characters/littleguy.json",
    "assets/characters/menupointer.json"
};

int numsounds = 2;
char *soundfiles[] = {
    "assets/vgmenuhighlight.wav",
    "assets/vgmenuselect.wav"
};

int numsprites = 9;
char *spritepaths[] = {
  "assets/sprites/menupointer.json",
  "assets/sprites/little_guy_walking_left.json",
  "assets/sprites/little_guy_walking_right.json",
  "assets/sprites/little_guy_walking_up.json",
  "assets/sprites/little_guy_walking_down.json",
  "assets/sprites/little_guy_facing_left.json",
  "assets/sprites/little_guy_facing_right.json",
  "assets/sprites/little_guy_facing_up.json",
  "assets/sprites/little_guy_facing_down.json"
};

char dirnamebuf[1024];


akerr_ErrorContext AKERR_NOIGNORE *akgltest_load_assets()
{
    PREPARE_ERROR(e);
    for ( int i = 0; i < numsprites ; i++) {
	strcpy((char *)&dirnamebuf, spritepaths[i]);
	SDL_Log("Loading sprite %s (%d of %d)....", (char *)&dirnamebuf, i, numsprites);
	PASS(e, akgl_sprite_load_json((char *)&dirnamebuf));
    }
    for ( int i = 0; i < numchars ; i++ ) {
	strcpy((char *)&dirnamebuf, characterpaths[i]);
	SDL_Log("Loading character %s (%d of %d)....", (char *)&dirnamebuf, i, numchars);
	PASS(e, akgl_character_load_json((char *)&dirnamebuf));
    }
    SUCCEED_RETURN(e);
}

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_registry_load_properties("assets/properties.json"));
	CATCH(e, akgl_render_init2d(&renderer));
	CATCH(e, akgl_physics_init_sidescroller(&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, AKERR_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 {
    } 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;
}


SDL_AppResult SDL_AppIterate(void *appstate)
{
    //SDL_FRect dest;
    //b2Vec2 position;

    PREPARE_ERROR(e);

    ATTEMPT {
	if ( AKGL_BITMASK_HAS(game.state.flags, AKGLTEST_STATE_QUIT) ) {
	    return SDL_APP_FAILURE;
	} else if ( AKGL_BITMASK_HAS(game.state.flags, AKGLTEST_STATE_RUNNING) ) {
	    CATCH(e, akgltest_iterate_running());
	} else if ( AKGL_BITMASK_HAS(game.state.flags, AKGLTEST_STATE_WAITFORINPUT) ) {
	    CATCH(e, akgltest_iterate_waitforinput());
	} else if ( AKGL_BITMASK_HAS(game.state.flags, AKGLTEST_STATE_MAPMENU) ) {
	    CATCH(e, akgltest_iterate_mapmenu());
	} 
    } CLEANUP {
    } PROCESS(e) {
    } HANDLE_DEFAULT(e) {
	LOG_ERROR(e);
	return SDL_APP_FAILURE;
    } FINISH_NORETURN(e);
    return SDL_APP_CONTINUE;
}

void SDL_AppQuit(void *appstate, SDL_AppResult result)
{
    /* SDL will clean up the window/renderer for us. */
    // SDL_DestroyTexture(ball.texture);
    //b2DestroyWorld(physicsWorldId);
    SDL_Log("Freeing music resources");
    if ( bgm != NULL ) {
	//Mix_FreeMusic(bgm);
    }
    SDL_Log("Quitting mixer");
    // Mix_Quit();
}
