#include "keyboard.h"
#include "idt.h"
#include "console.h"
#include "port.h"
#include <stdint.h>

// PS/2 keyboard interrupt handler
// PS/2 keyboard interrupt handler
void ps2_keyboard_handler(void) {
    uint8_t scancode;

    // Save state
    asm volatile (
        "pusha\n"              // Save general-purpose registers
        "pushf\n"              // Save flags register
        "cli\n"                // Clear interrupts
    );

    // Read the keyboard data from the PS/2 controller
    scancode = inb(0x60);

    // Print the scancode
    print("Scancode received: ");
    // Convert scancode to hexadecimal and print
    char hex[3];
    hex[0] = "0123456789ABCDEF"[(scancode >> 4) & 0xF];
    hex[1] = "0123456789ABCDEF"[scancode & 0xF];
    hex[2] = '\0';
    print(hex);
    print("\n");

    // Send end of interrupt (EOI) to the Master PIC
    outb(0x20, 0x20);

    // Restore state
    asm volatile (
        "popf\n"               // Restore flags register
        "popa\n"               // Restore general-purpose registers
        "iret\n"               // Return from interrupt
    );
}


// Function to initialize the PS/2 keyboard
void keyboard_init() {
    // Set up the IDT entry for IRQ1 (PS/2 keyboard)
    set_idt_entry(0x21, (uint32_t) ps2_keyboard_handler, 0x08, 0x8E);

    // Enable IRQ1 (keyboard) on PIC
    outb(0x21, inb(0x21) & ~(1 << 1));

    // Enable interrupts
    asm volatile("sti");
}
