class aip_parser:
    def digitalWrite(self, args):
        if len(args) != 2:
            return
        self.robot.digitalWrite(*map(int, args))
    
    def analogWrite(self, args):
        if len(args) != 2:
            return
        self.robot.analogWrite(*map(int, args))
        
    def updateDt(self, args):
        if len(args) != 1:
            return
        self.robot.setTime(int(args[0]))
        
    cmds = {
        "dw" : digitalWrite,
        "aw" : analogWrite,
        "dt" : updateDt,
    }
        
    def __init__(self, stdin, stdout, robot):
        self.stdin = stdin
        self.stdout = stdout
        self.cmd_buff = ""
        self.robot = robot
    
    def poll(self):
        c=self.stdout.read(1)
        if not c:
            return True
        if c == b'*':
            return False
        try:
            print(c.decode(), end='')
        except UnicodeDecodeError:
            pass
        if len(self.cmd_buff)==0:
            if c != b'$':
                return True
            self.cmd_buff = "_"
        else:
            if c == b';':
                self.parse_line()
            else:
                try:
                    self.cmd_buff += c.decode()
                except UnicodeDecodeError:
                    pass
        return True
    
    def parse_line(self):
        cmd = self.cmd_buff[1:].split(',')
        cmdFct = self.cmds.get(cmd[0])
        if cmdFct:
            cmdFct(self, cmd[1:])
        self.cmd_buff = ""
        
    def send_pin_state(self):
        for ind, p in enumerate(self.robot.pins):
            self.stdin.write(bytes(f"${ind},{p};", "utf-8"))
        for ind, p in enumerate(self.robot.dists):
            if not p:
                p = -10
            else:
                p = int(1000*p)
            print("#######", p)
            self.stdin.write(bytes(f"${-ind-1},{p};", "utf-8"))