#include "state.h"
#include "scenes/scene.h"
#include "scenes/title.h"

#include "twn_game_api.h"

#include <stdio.h>
#include <malloc.h>
#include <stdint.h>


void game_tick(void) {
    if (ctx.initialization_needed) {
        if (!ctx.udata) {
            ctx.udata = calloc(1, sizeof (State));

            State *state = ctx.udata;
            state->ctx = &ctx;
            state->scene = title_scene(state);
        }
    }

    State *state = ctx.udata;

    input_action("debug_toggle", "BACKSPACE");
    input_action("debug_dump_atlases", "HOME");

    if (input_action_just_pressed("debug_toggle")) {
        ctx.debug = !ctx.debug;
    }

    if (input_action_just_pressed("debug_dump_atlases")) {
        textures_dump_atlases();
    }

    state->scene->tick(state);

    /* there's a scene switch pending, we can do it now that the tick is done */
    if (state->next_scene != NULL) {
        state->scene->end(state);
        state->scene = state->next_scene;
        state->is_scene_switching = false;
        state->next_scene = NULL;
    }
}


void game_end(void) {
    State *state = ctx.udata;
    state->scene->end(state);
    free(state);
}
