#include "twn_timer_c.h"
#include "twn_engine_context_c.h"

#include <SDL2/SDL.h>
#include <stdlib.h>

static SDL_TimerID sanity_timer;

#define SANITY_TIMER_MESSAGE_FMT "Game tick exeeded its allocated time (%u milliseconds), application is closing"

/* stop application */
static uint32_t sanity_timer_handler(uint32_t interval, void *data) {
    (void)data;

    size_t text_str_len = snprintf(NULL, 0, SANITY_TIMER_MESSAGE_FMT, interval) + 1;
    char *text_str = SDL_malloc(text_str_len);
    snprintf(text_str, text_str_len, SANITY_TIMER_MESSAGE_FMT, interval);
    SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "sanity timer", text_str, ctx.window);
    SDL_free(text_str);

    /* TODO: figure out the most portable way to do it */
    /* TODO: different type of behavior is possible, especially for debugging */
    exit(EXIT_FAILURE);
}


bool start_sanity_timer(uint32_t milliseconds_to_expire) {
    if (!sanity_timer) {
        sanity_timer = SDL_AddTimer(milliseconds_to_expire, sanity_timer_handler, NULL);
    }

    return sanity_timer != 0;
}


void end_sanity_timer(void) {
    SDL_RemoveTimer(sanity_timer);
    sanity_timer = 0;
}
