package fabrik.simulator.pic16f84;

public class PreScaler {
    private static final int PSA = 0x3;
    private static final int OPTION = 0x81;

    private static int scaler = 0b111;

    public static boolean isPrescalerOnTimer (){
        return DataRegister.getDirectBit(OPTION, PSA) == 0;
    }



    public static int getScaler() {
        return scaler;
    }

    public static int getFactor () {
        int scale = DataRegister.getDirectRegister(OPTION) & 0b111;
        int timer = isPrescalerOnTimer() ? 1 : 0;
        return (int) Math.pow (2, scale+timer);
    }

    public static void reset (){
        DataRegister.setDirectBit(OPTION, 0, 0);
        DataRegister.setDirectBit(OPTION, 1, 0);
        DataRegister.setDirectBit(OPTION, 2, 0);
    }

    public static void resetFromRegister() {
        scaler = getFactor();
    }

    public static void decrement(boolean manual) {
        scaler--;
        if (scaler == 0) {
            scaler = getFactor();
            Timer.increment(manual);
        }
    }
}
