#include "io.h"
#include "tty.h"

// The Scan Code Map - Every key on the keyboard!
char kbd_map[] = {
    0,  27, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', '\b',
    '\t', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\n',
    0, 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'', '`', 0,
    '\\', 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', 0, '*', 0, ' '
};

static uint8_t last_scancode = 0;

void update_keyboard() {
    // Check if the keyboard has data ready (Status Port 0x64, Bit 0)
    if (inb(0x64) & 1) {
        uint8_t scancode = inb(0x60);
        
        // If the scancode is the SAME as the last one, skip it
        // This prevents one tap from typing 50 letters on your fast laptop
        if (scancode == last_scancode) {
            return; 
        }

        last_scancode = scancode;

        // Key Pressed (scancode < 0x80)
        if (scancode < 0x80) {
            char c = kbd_map[scancode];
            if (c > 0) {
                tty_putchar(c);
            }
        } else {
            // Key Released (scancode >= 0x80)
            // We reset last_scancode so you can press the same key again later
            last_scancode = 0; 
        }
    }
}