#include "input.h"
#include <SDL2/SDL_scancode.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>


keyEvent_t * events[SDL_NUM_SCANCODES];
int event_counts[SDL_NUM_SCANCODES];

void input_init(void) {
    memset(events, 0, SDL_NUM_SCANCODES * sizeof(keyEvent_t *));
    memset(event_counts, 0, SDL_NUM_SCANCODES * sizeof(int));
}

void input_poll(SDL_Scancode code) {
    printf("Scancode: %d\n", code);
    keyEvent_t * handlers = events[code];
    for(int i = 0; i < event_counts[code]; i++) {
        handlers[i]();
    }
}


void input_listen(SDL_Scancode code, keyEvent_t handler) {
    event_counts[code]++;
    events[code] = (keyEvent_t *)realloc(events[code], event_counts[code] * sizeof(keyEvent_t));
    events[code][event_counts[code] - 1] = handler;
}

void input_removeListener(SDL_Scancode code, keyEvent_t handler) {
    bool found = false;
    for(int i = 0; i < event_counts[code]; i++) {
        if(events[code][i] == handler) {
            found = true;
            break;
        }
        if(found) {
            if(i == event_counts[code] - 1) {
                break;
            }
            events[code][i] = events[code][i + 1];
        }
    }
    event_counts[code]--;
}
