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


keyEvent_t * eventsKeyDown[SDL_NUM_SCANCODES];
int eventKeyDown_counts[SDL_NUM_SCANCODES];

keyEvent_t * eventsKeyUp[SDL_NUM_SCANCODES];
int eventKeyUp_counts[SDL_NUM_SCANCODES];

void input_init(void) {
    memset(eventsKeyDown, 0, SDL_NUM_SCANCODES * sizeof(keyEvent_t *));
    memset(eventKeyDown_counts, 0, SDL_NUM_SCANCODES * sizeof(int));

    memset(eventsKeyUp, 0, SDL_NUM_SCANCODES * sizeof(keyEvent_t *));
    memset(eventKeyUp_counts, 0, SDL_NUM_SCANCODES * sizeof(int));
}

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

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


void input_listenKeyDown(SDL_Scancode code, keyEvent_t handler) {
    eventKeyDown_counts[code]++;
    eventsKeyDown[code] = (keyEvent_t *)realloc(eventsKeyDown[code], eventKeyDown_counts[code] * sizeof(keyEvent_t));
    eventsKeyDown[code][eventKeyDown_counts[code] - 1] = handler;
}

void input_listenKeyUp(SDL_Scancode code, keyEvent_t handler) {
    eventKeyUp_counts[code]++;
    eventsKeyUp[code] = (keyEvent_t *)realloc(eventsKeyUp[code], eventKeyUp_counts[code] * sizeof(keyEvent_t));
    eventsKeyUp[code][eventKeyUp_counts[code] - 1] = handler;
}

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

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