#include <printf.h>
#include <shade/platform/interrupts/isr.h>
#include <shade/platform/interrupts/pic.h>

void exception_handler(uint8_t vector, uint16_t err) {
    (*interrupt_handlers[vector])(vector, err);
    if (vector >= IRQ_MIN && vector <= IRQ_MAX) {
        // needs EOI
        pic_send_eoi(vector);
    }
}

int register_interrupt_handler(int vector, void (*handler)(uint8_t, uint16_t)) {
    interrupt_handlers[vector] = handler;
}

int unregister_interrupt_handler(int vector) {
    interrupt_handlers[vector] = default_handler;
}

void default_handler(uint8_t vector, uint16_t err) {
    kprintf(" %i: cpu: check_exception 0x%x err_code => %x\n", err_count, vector, err);
    kprintf(" %i: cpu: no irq for vector 0x%x\n", err_count, vector);
    err_count++;
    if (err_count > ERR_MAX) {
        kprintf("cpu: ierr hit err_max, halt\n");
        __asm__ __volatile__("cli; hlt");
    }
}

void fill_isr() {
    for (int i = 0; i < 256; i++) {
        register_interrupt_handler(i, default_handler);
    }
}