#include <interrupts.h>
#include <stack.h>
#include <emu.h>

void int_handle(cpu_context *ctx, u16 address) {
    emu_cycles(2);
    stack_push16(ctx->regs.pc);
    emu_cycles(2);
    ctx->regs.pc = address;
    //emu_cycles(1);
}

bool int_check(cpu_context *ctx, u16 address, interrupt_type t){
    if(ctx->int_flags & t && ctx->ie_register & t) {
        int_handle(ctx, address);
        ctx->int_flags &= ~t;
        ctx->halted = false;
        ctx->int_master_enabled = false;
        return true;
    }
    return false;
}

void cpu_request_interrupt(interrupt_type t);

void cpu_handle_interrupts(cpu_context *ctx) {
    if (int_check(ctx, 0x40, IT_VBLANK)) {
        //printf("VBLANK!\n");
    } else if(int_check(ctx, 0x48, IT_LCD_STAT)){
        //printf("LCD!\n");
    } else if(int_check(ctx, 0x50, IT_TIMER)){
        //printf("TIMER!\n");
    } else if(int_check(ctx, 0x58, IT_SERIAL)){
        //printf("Serial!\n");
    } else if(int_check(ctx, 0x60, IT_JOYPAD)){
        //printf("Joy!\n");
    }
}