package maschine;

public class Ueberwachung implements UeberwachungInterface {

    private MInterface maschine;
    private static int ZYKLUS = 1000; // Waertezeit in ms
    private boolean alarm;
    private int fehler;
    private int alterWert;
    private boolean geradeGestartet = true;

    public Ueberwachung() {
    }

    @Override
    public void ueberwachen() {
        while (!alarm) {
            try {
                Thread.sleep(ZYKLUS);
            } catch (InterruptedException ex) {
            }
            this.sensorenLesen();
        }
    }

    @Override
    public void sensorenLesen() {
        boolean allesOK = true;
        try {
            int wert = this.maschine.getWert1();
            if (!this.geradeGestartet && Math.abs(wert - this.alterWert) > 5) {
                this.fehler++;
                allesOK = false;
            } else {
                this.geradeGestartet = false;
            }
            this.alterWert = wert;
        } catch (NetworkException ex) {
            this.fehler++;
            allesOK = false;
        } catch (HardwareException ex) {
            this.fehler++;
            allesOK = false;
        }
        try {
            String zustand = this.maschine.getZustand1();
            if (zustand.equals("defekt")) {
                this.fehler = 3;
                allesOK = false;
            }
        } catch (NetworkException ex) {
            this.fehler++;
            allesOK = false;
        }
        if (this.fehler == 3) {
            this.alarm = true;
        }
        if (allesOK) {
            this.fehler = 0;
        }
    }

    public MInterface getMaschine() {
        return maschine;
    }

    @Override
    public void setMaschine(MInterface maschine) {
        this.maschine = maschine;
    }

    @Override
    public boolean isAlarm() {
        return alarm;
    }

    public void setAlarm(boolean alarm) {
        this.alarm = alarm;
    }

}
