package fabrik.simulator.pic16f84;

public class Interrupts {
    private static final int INTCON = 0xB;
    private static final int T0IF = 0x2;
    private static final int ISR = 0x4;
    private static final int GIE = 0x7;
    private static final int T0IE = 0x5;
    private static final int RBIE = 0x3;
    private static final int RBIF = 0x0;
    private static final int INTEDG = 0x6;
    private static final int OPTION = 0x81;
    private static final int INTE = 0x4;
    private static final int INTF = 0x1;

    public static void triggerTMR0(boolean manual) {
        triggerInterrupt(T0IF, T0IE);
        if (manual)
            DataRegister.increasePC();
    }

    private static void triggerInterrupt(int flag, int enableFlag) {
        DataRegister.setBit(INTCON, flag);
        enableFlag = DataRegister.getDirectBit(INTCON, enableFlag);
        int globalFlag = DataRegister.getDirectBit(INTCON, GIE);
        if (enableFlag == 1) {
            Controller_Frontend.wakeUpFromSleep();
            if (globalFlag == 1) {
                DataRegister.clearBit(INTCON, GIE);
                Commands.CALL(ISR);
            }
        }
    }


    public static void triggerRBInterrupt(int oldValue, int newValue) {
        if (newValue != oldValue){
            triggerInterrupt(RBIF, RBIE);
            DataRegister.increasePC();
        }
    }

    public static void triggerRB0Interrupt(int oldValue, int newValue){
        if (newValue != oldValue){
            int intedg = DataRegister.getDirectBit(OPTION, INTEDG);
            if (intedg == 1) {
                if (oldValue == 0 && newValue == 1)
                    triggerInterrupt(INTF, INTE);
            } else {
                if (oldValue == 1 && newValue == 0)
                    triggerInterrupt(INTF, INTE);
            }
            DataRegister.increasePC();
        }
    }


}
