package fabrik.simulator.pic16f84;

public class WatchdogTimer {
    private static long watchdogTime;
    private static long lastReset = 0;
    private static boolean enabled = false;

    private static long getTimeFromRegister() {
        return (PreScaler.isPrescalerOnTimer()) ? 18L : PreScaler.getFactor() * 18L;
    }

    public static void testAndTrigger() {
        watchdogTime = getTimeFromRegister() * 1000;
        if (enabled) {
            System.err.println("Remaining: " + ((watchdogTime + lastReset - 1) - Commands.getTotalExecutionTime()));
            if (Commands.getTotalExecutionTime() >= (watchdogTime + lastReset - 1)) {
                System.err.println("Watchdog Timer triggered");
                DataRegister.clearBit(3, 4);
                lastReset = Commands.getTotalExecutionTime();
                Controller_Frontend.stopRunFromBackend();
            }
        }
    }

    public static void reset (){
        lastReset = Commands.getTotalExecutionTime();
        PreScaler.reset();
        DataRegister.setBit(3, 3);
        DataRegister.setBit(3, 4);
    }

    public static void enable() {
        enabled = true;
    }

    public static void disable() {
        enabled = false;
    }
}
