package fabrik.simulator.pic16f84;

public class Timer {
    private static final int TIMERREG = 0x1;
    private static final int T0IF = 0x2;
    private static final int T0SE = 0x4;
    private static final int T0CS = 0x5;
    private static final int INTCON = 0x0B;
    private static final int OPTION = 0x81;

    private static int oldpin = 0;


    public static void cycles(int cycles){
        if (DataRegister.getDirectBit(OPTION, T0CS) == 0){
            if (PreScaler.isPrescalerOnTimer()){
                for (int i = 0; i < cycles; i++){
                    PreScaler.decrement();
                }
            } else {
                increment();
            }
        }
    }

    public static void incrementFromPin (int register){
        if (DataRegister.getDirectBit(OPTION, T0CS) == 1){
            int newpin = (register >> 4) & 1;
            if (newpin != oldpin) {
                System.out.println(newpin + " " + oldpin);
                if (DataRegister.getDirectBit(OPTION, T0SE) == 0) {
                    // Low to high
                    if (newpin == 1 && oldpin == 0) {
                        if (PreScaler.isPrescalerOnTimer())
                            PreScaler.decrement();
                        else
                            increment();
                    }
                } else {
                    // High to low
                    if (newpin == 0 && oldpin == 1) {
                        if (PreScaler.isPrescalerOnTimer())
                            PreScaler.decrement();
                        else
                            increment();
                    }
                }
                oldpin = newpin;
            }
        }
    }

    public static void increment() {
        int timer = DataRegister.getDirectRegister(TIMERREG);
        timer++;
        if (timer > 0xFF){
            DataRegister.setDirectRegister(TIMERREG, 0);
            DataRegister.setBit(INTCON, T0IF);
        } else {
            DataRegister.setDirectRegister(1, timer);
        }
    }
}
