# RECEIVER  (put this on ONE micro:bit and plug it into the Mac with USB)
#
# Hears the student buzzers by radio. The first valid buzz wins and locks the
# rest. Tells the Mac who buzzed, and takes commands from it over USB.
# Button A on the receiver = open the buzzers again.
#
# Display: small dot = closed, square = open, a number = who buzzed

from microbit import *
import radio

GROUP = 42          # must match buzzer.py
MOST = 30

radio.config(group=GROUP, power=6, length=120, queue=20)
radio.on()

DOT = Image("00000:00000:00500:00000:00000")

is_open = False
winner = 0
excluded = []       # numbers (as text) who are out for this question
heard = {}          # number -> when we last told the Mac about it
last_radio = 0
last_serial = 0
text = ""


def state():
    if winner:
        return "L:%d" % winner
    if is_open:
        return "O:" + ",".join(excluded)
    return "W"


def announce():
    global last_radio, last_serial
    message = state()
    for _ in range(3):
        radio.send(message)
    print("STATE:" + message)
    last_radio = last_serial = running_time()


def draw():
    if winner >= 10:
        display.scroll(str(winner), delay=90, wait=False, loop=True)
    elif winner:
        display.show(str(winner))
    else:
        display.show(Image.SQUARE if is_open else DOT)


def to_number(value):
    if value.isdigit() and 1 <= int(value) <= MOST:
        return int(value)
    return 0


def command(line):
    global is_open, winner, excluded
    if line == "STATUS":
        print("STATE:" + state())
        return
    if line == "CLOSE":
        is_open = False
        excluded = []
    elif line.startswith("OPEN:"):
        is_open = True
        excluded = [v for v in line[5:].split(",") if to_number(v)]
    else:
        return
    winner = 0
    announce()
    draw()


print("READY")
announce()
draw()

while True:
    while True:
        try:
            message = radio.receive()
        except ValueError:
            message = None
        if not message:
            break
        n = to_number(message[1:])
        if not n:
            continue
        if message[0] == "B" and is_open and not winner and str(n) not in excluded:
            winner = n
            is_open = False
            print("BUZZ:%d" % n)
            announce()
            draw()
        elif message[0] == "H" and running_time() - heard.get(n, -10000) > 2000:
            heard[n] = running_time()
            print("SEEN:%d" % n)

    if uart.any():
        data = uart.read()
        if data:
            try:
                text += str(data, "utf-8")
            except Exception:
                text = ""
            while "\n" in text:
                line, text = text.split("\n", 1)
                command(line.strip())
            if len(text) > 200:
                text = ""

    if button_a.was_pressed():
        print("BUTTON")          # the Mac decides what happens

    now = running_time()
    if now - last_radio > 200:   # keep reminding the buzzers
        radio.send(state())
        last_radio = now
    if now - last_serial > 1000:  # lets the Mac know we are here
        print("STATE:" + state())
        last_serial = now

    sleep(2)
