package fabrik.simulator.pic16f84;

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

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

    public static void testAndTrigger() {
        watchdogTime = getTimeFromRegister() * 1000;
        if (enabled) {
            if (realtimer >= (watchdogTime + lastReset - 1)) {
                DataRegister.clearBit(3, 4);
                lastReset = Commands.getTotalExecutionTime();
                Controller_Frontend.stopRunFromBackend("Watchdog Timer");
            }
            else {
                rawtimer++;
                realtimer = (long) (rawtimer * Controller_Frontend.getExecutionTimeMultiplier());
            }
        }
    }

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

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

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

    public static long get (){
        return realtimer;
    }
}
