import select
import sys
import time
from machine import Pin
from neopixel import NeoPixel

print("Starting USB UART")
print("...")

NEO_PIXELS = NeoPixel(Pin(48), 1)


def parse_cmd(raw_bytes):
    # Drop the last element
    raw_cmds = raw_bytes.strip().split(';')
    cmds = []
    for cmd in raw_cmds:
        try:
            led, red, green, blue = cmd.split(',')
            # Still strings so zero is true here
            if all([led, red, green, blue]) and len(cmd.split(',')) == 4:
                cmds.append(tuple([int(led), tuple([int(red), int(green), int(blue)])]))
        except ValueError:
            continue
    return cmds


def main():
    print("Waiting for commands...")

    while True:
        if select.select([sys.stdin], [], [], 0)[0]:
            raw_cmds = sys.stdin.readline()
            cmds = parse_cmd(raw_cmds)
            # print(f"Parsed: {cmds}")
            if cmds:
                for led_cmd in cmds:
                    led_id, led_value = led_cmd
                    NEO_PIXELS[led_id] = led_value
                NEO_PIXELS.write()

main()