import time

from utils import send_update

# this is driving a SSR that's powering a AC-powered humidifier
# we don't need voltage readings for this one
class HumidifierV3:
    def __init__(self, humidifier_id="humidifier"):
        self.last_toggle = 0
        self.last_state = None
        self.cooldown = 5
        self.humidifier_id = humidifier_id

    def set(self, s, on):
        if on != self.last_state:
            if (time.time() - self.last_toggle) < self.cooldown:
                return
        if on:
            s.write(b"Z")
            s.flush()
        else:
            s.write(b"z")
            s.flush()
        if self.last_state != on:
            self.last_toggle = time.time()
            if on:
                print("send {} on".format(self.humidifier_id))
            else:
                print("send {} off".format(self.humidifier_id))
            send_update({"status": {self.humidifier_id: on}})

        self.last_state = on

    # TODO: read this from Arduino to verify the pin state
    def update(self, val):
        self.last_state = (val != 0)

    @property
    def on(self):
        return self.last_state is not None and self.last_state

    @property
    def off(self):
        return self.last_state is not None and not self.last_state