package fabrik.simulator.pic16f84;

import fabrik.simulator.pic16f84.interfaces.*;

public class WatchdogTimer extends PICComponent implements WatchdogTimerInterface {
    private long watchdogTime;
    private double lastReset = 0;
    private boolean enabled = false;
    private long rawtimer = 0;
    private long realtimer = 0;

    public WatchdogTimer(){
    }
        
    private long getTimeFromRegister() {
        return (preScaler.isPrescalerOnTimer()) ? 18L : preScaler.getFactor() * 18L;
    }

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

    public void reset (){
        lastReset = executionTime.getTotalExecutionTime();
        rawtimer = 0;
        realtimer = 0;
        preScaler.reset();
        dataRegister.setBit(3, 3);
        dataRegister.setBit(3, 4);
    }

    public void enable() {
        enabled = true;
    }

    public void disable() {
        enabled = false;
    }

    public long get (){
        return realtimer;
    }

    @Override
    public void initialize(PICComponentLocator locator) {
        super.initialize(locator);
    }
}
