#include "device/device.h"
#include "sys/sys.h"
#include "sys_input.h"

sys_i32 sys_input_down_frames[DEVICE_BUTTON_N];

void sys_input_update() {
    for (DeviceButton db = 0; db < DEVICE_BUTTON_N; db++) {
        if (device_buttons[db]) {
            sys_input_down_frames[db] += 1;
        } else {
            sys_input_down_frames[db] = 0;
        }
    }
}

void sys_input_reset() {
    for (DeviceButton db = 0; db < DEVICE_BUTTON_N; db++) {
        sys_input_down_frames[db] = 0;
    }
}

bool sys_btn(DeviceButton button) {
    if (button >= DEVICE_BUTTON_N) { return false; }
    return sys_input_down_frames[button] >= 1;
}

bool sys_btnp(DeviceButton button, bool repeat) {
    if (button >= DEVICE_BUTTON_N) { return false; }
    if (sys_input_down_frames[button] == 1) { return true; }
    if (!repeat) { return false; }
    // 31 and every 8 frames after that
    if (sys_input_down_frames[button] >= 31 && (sys_input_down_frames[button] - 31) % 8 == 0) { 
        return true; 
    }
    return false;
}