#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 <akerror.h>
#include <akgl/assets.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/error.h>

#include <unistd.h>

SDL_AppResult SDL_AppInit(void **appstate, int argc, char *argv[])
{
    PREPARE_ERROR(errctx);
    akgl_Actor *actorptr = NULL;
    int gamepadids[32];
    char *characterjson = NULL;
    char pathbuf[4096];
    char cwdbuf[1024];

    if ( argc < 3 ) {
	SDL_Log("charviewer [CHARACTER_FILE] [SPRITE ...]");
	return SDL_APP_FAILURE;
    }

    *appstate = (void *)&akgl_game.state;
    characterjson = argv[1];
    memset((char *)&pathbuf, 0x00, 4096);
    memset((char *)&cwdbuf, 0x00, 1024);

    ATTEMPT {

	FAIL_ZERO_BREAK(errctx, appstate, AKERR_NULLPOINTER, "NULL appstate pointer");
	FAIL_ZERO_BREAK(errctx, getcwd((char *)&cwdbuf, 1024), AKERR_NULLPOINTER, "Couldn't get current working directory");

	strcpy((char *)&akgl_game.name, "charviewer");
	strcpy((char *)&akgl_game.version, "0.0.1");
	strcpy((char *)&akgl_game.uri, "net.aklabs.libakgl.charviewer");
	CATCH(errctx, akgl_game_init());
	CATCH(errctx, akgl_set_property("game.screenwidth", "640"));
	CATCH(errctx, akgl_set_property("game.screenheight", "480"));
	CATCH(errctx, akgl_render_2d_init(akgl_renderer));
	CATCH(errctx, akgl_physics_init_null(akgl_physics));

    } CLEANUP {
    } PROCESS(errctx) {
    } HANDLE_DEFAULT(errctx) {
	LOG_ERROR(errctx);
	return SDL_APP_FAILURE;
    } FINISH_NORETURN(errctx);

    for ( int i = 2; i < argc ; i++) {
	ATTEMPT {
	    if ( argv[i][0] != '/' ) {
		sprintf((char *)&pathbuf, "%s/%s", (char *)&cwdbuf, argv[i]);
	    } else {
		sprintf((char *)&pathbuf, "%s", argv[i]);
	    }
	    SDL_Log("Loading sprite %s...", (char *)&pathbuf);
	    CATCH(errctx, akgl_sprite_load_json((char *)&pathbuf));
	} CLEANUP {
	} PROCESS(errctx) {
	} HANDLE_DEFAULT(errctx) {
	    LOG_ERROR(errctx);
	    return SDL_APP_FAILURE;
	} FINISH_NORETURN(errctx);
	memset((char *)&pathbuf, 0x00, 4096);
    }

    ATTEMPT {
	if ( characterjson[0] != '/' ) {
	    sprintf((char *)&pathbuf, "%s/%s", (char *)&cwdbuf, characterjson);
	} else {
	    sprintf((char *)&pathbuf, "%s", characterjson);
	}
	SDL_Log("Loading character %s...", (char *)&pathbuf);
	CATCH(errctx, akgl_character_load_json((char *)&pathbuf));
	CATCH(errctx, akgl_heap_next_actor(&actorptr));
	CATCH(errctx, akgl_actor_initialize((akgl_Actor *)actorptr, "player"));
	actorptr->basechar = SDL_GetPointerProperty(
	    AKGL_REGISTRY_CHARACTER,
	    "little guy",
	    NULL);
	FAIL_ZERO_BREAK(errctx, 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_DOWN);
	actorptr->x = 320;
	actorptr->y = 240;
	actorptr->visible = true;

	// Open the first gamepad
	FAIL_ZERO_BREAK(errctx, SDL_GetGamepads((int *)&gamepadids), AKGL_ERR_SDL, "%s", SDL_GetError());
	SDL_Log("Opening gamepad %d", gamepadids[0]);
	FAIL_ZERO_BREAK(errctx, SDL_OpenGamepad(gamepadids[0]), AKGL_ERR_SDL, "%s", SDL_GetError());
	CATCH(errctx, akgl_controller_default(0, "player", 0, gamepadids[0]));

    } CLEANUP {
    } PROCESS(errctx) {
    } HANDLE_DEFAULT(errctx) {
	LOG_ERROR(errctx);
	return SDL_APP_FAILURE;
    } FINISH_NORETURN(errctx);

    return SDL_APP_CONTINUE;
}

SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event)
{
    PREPARE_ERROR(errctx);

    ATTEMPT {
	FAIL_ZERO_BREAK(errctx, appstate, AKERR_NULLPOINTER, "NULL appstate pointer");
	FAIL_ZERO_BREAK(errctx, event, AKERR_NULLPOINTER, "NULL event pointer");

	CATCH(errctx, 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 {
    } PROCESS(errctx) {
    } FINISH_NORETURN(errctx);
    return SDL_APP_CONTINUE;  /* carry on with the program! */
}

SDL_AppResult SDL_AppIterate(void *appstate)
{
    int i = 0;
    akgl_Iterator opflags;

    PREPARE_ERROR(errctx);

    AKGL_BITMASK_CLEAR(opflags.flags);
    AKGL_BITMASK_ADD(opflags.flags, AKGL_ITERATOR_OP_UPDATE);
    AKGL_BITMASK_ADD(opflags.flags, AKGL_ITERATOR_OP_RENDER);
    ATTEMPT {
	CATCH(errctx, akgl_draw_background(akgl_renderer, (int)akgl_camera->w, (int)akgl_camera->h));
	CATCH(errctx, akgl_tilemap_draw(akgl_gamemap, akgl_camera, i));
	SDL_EnumerateProperties(AKGL_REGISTRY_ACTOR, &akgl_registry_iterate_actor, (void *)&opflags);
    } CLEANUP {
    } PROCESS(errctx) {
    } HANDLE_DEFAULT(errctx) {
	LOG_ERROR(errctx);
	return SDL_APP_FAILURE;
    } FINISH_NORETURN(errctx);
    SDL_RenderPresent(akgl_renderer->sdl_renderer);
    return SDL_APP_CONTINUE;
}

void SDL_AppQuit(void *appstate, SDL_AppResult result)
{
}
