import time
class ClimateChamber():
    def __init__(self, daemon, ip:str, port:int, threshold=1):
        self.daemon = daemon
        res = self.daemon.send_command("open", [
            {"type": "string", "value": "ClimateChamber"},
            {"type": "dict", "value": {
                "ip": ip,
                "port": port
        }}])

        self.id = res["reference_id"]
        self.threshold = threshold


    def start(self, temp:float, hum:float, block=False):
        self.daemon.send_command("execute", 
        [
            {"type": "string", "value": self.id},
            {"type": "string", "value": "start"},
            {"type": "list", "value": [
                {"type": "float", "value": temp},
                {"type": "float", "value": hum},
            ]} 
        ])

        if not block:
            return

        status = self.get_status()
        while not (temp - self.threshold < status["temperature"] < temp + self.threshold):
            time.sleep(1)
            print(f"Waiting for CC command, target: {temp}, temp: {status['temperature']}, hum: {status['humidity']}")
            status = self.get_status()
        print("CC target reached!.")

    def stop(self):
        self.daemon.send_command("execute", 
        [
            {"type": "string", "value": self.id},
            {"type": "string", "value": "stop"},
            {"type": "list", "value": [
            ]} 
        ])

    def get_status(self):
        return self.daemon.send_command("execute", 
        [
            {"type": "string", "value": self.id},
            {"type": "string", "value": "get_status"},
            {"type": "list", "value": []} 
        ])

    def get_device_info(self):
        return self.daemon.send_command("execute", 
        [
            {"type": "string", "value": self.id},
            {"type": "string", "value": "get_info"},
            {"type": "list", "value": []} 
        ])