#include "core/jail/jinput.hpp"

#include <string>

#include "core/system/director.hpp"

// keystates és actualitzat per SDL internament. Des del joc només fem lectures.
const bool* keystates = nullptr;
Uint8 cheat[5];
bool key_pressed = false;
int waitTime = 0;

void JI_DisableKeyboard(Uint32 time) {
    waitTime = time;
}

static bool input_blocked = false;

void JI_SetInputBlocked(bool blocked) {
    input_blocked = blocked;
}

void JI_moveCheats(Uint8 new_key) {
    cheat[0] = cheat[1];
    cheat[1] = cheat[2];
    cheat[2] = cheat[3];
    cheat[3] = cheat[4];
    cheat[4] = new_key;
}

void JI_Update() {
    // El director ha processat tots els events. Ací només refresquem
    // el snapshot del teclat i consumim el flag de tecla polsada.
    if (keystates == nullptr) {
        keystates = SDL_GetKeyboardState(NULL);
    }

    if (waitTime > 0) waitTime--;

    // Consumim el flag de "alguna tecla no-GUI polsada" del director
    key_pressed = Director::get()->consumeKeyPressed();
}

bool JI_KeyPressed(int key) {
    if (waitTime > 0 || keystates == nullptr) return false;
    // Input bloquejat (p.ex. menú flotant obert)
    if (input_blocked) return false;
    // ESC bloquejada pel Director (primera pulsació mostra notificació)
    if (key == SDL_SCANCODE_ESCAPE && Director::get()->isEscBlocked()) return false;
    return keystates[key] != 0;
}

bool JI_CheatActivated(const char* cheat_code) {
    bool found = true;
    for (size_t i = 0; i < strlen(cheat_code); i++) {
        if (cheat[i] != cheat_code[i]) found = false;
    }
    return found;
}

bool JI_AnyKey() {
    return waitTime > 0 ? false : key_pressed;
}
