# vim: ts=4 et sts=4 sw=4 autoindent

import threading
import time

from sndcs_common.SndcsExceptions import SndcsHeartbeatError

from sndcs_common.Logger import logger
log = logger.getLogger("Heartbeat Monitor")

class HeartbeatMonitor(threading.Thread):

    def __init__(self, callback):
        """callback is called when the heartbeat flatlines."""
        threading.Thread.__init__(self)
        self.setDaemon(1)
        self.callback = callback
        self.last_beat = time.time()
        self.quit = False

    def run(self):
        print "Starting Heartbeat Monitor..."
        log.debug("Starting Heartbeat Monitor")
        while not self.quit:
            if time.time() - self.last_beat > 21: # Missed four beats
                print "Heartbeat has flatlined!"
                log.critical("Heartbeat has flatlined! Time is now %s and last heartbeat was %s", time.time(), self.last_beat)
                self.callback(SndcsHeartbeatError("SaberNet DCS Heartbeat Monitor flatline.\nConnection to DCS server lost!"))
                return
            # Peek every second to see if we need to quit
            for x in xrange(5):
                if not self.quit:
                    time.sleep(1)
                else:
                    return

    def update(self, event):
        self.last_beat = time.time()
