import display
import utime
import buttons
import color
import leds

_rand = 123456789
def rand():
    global _rand
    _rand = (1103515245 * _rand + 12345) & 0xffffff
    return _rand

alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"

gs = 160
colors = [ ((i>>2)*gs, (i>>1&1)*gs, (i&1)*gs) for i in range(1, 8) ]

def button_events():
    """Iterate over button presses (event-loop)."""
    yield 0
    button_pressed = False

    while True:
        v = buttons.read(buttons.BOTTOM_LEFT | buttons.BOTTOM_RIGHT | buttons.TOP_RIGHT)

        if v == 0:
            button_pressed = False

        if not button_pressed and v & buttons.BOTTOM_LEFT != 0:
            button_pressed = True
            yield buttons.BOTTOM_LEFT

        if not button_pressed and v & buttons.BOTTOM_RIGHT != 0:
            button_pressed = True
            yield buttons.BOTTOM_RIGHT

        if not button_pressed and v & buttons.TOP_RIGHT != 0:
            button_pressed = True
            yield buttons.TOP_RIGHT

def draw_menu(disp, cur_selected = ""):
    disp.clear()
    disp.print("Enter:", fg=color.CHAOSBLUE, posy=20)
    disp.print(" " + cur_selected, posy=40)
    disp.update()

def main():
    disp = display.Display()
    cur_str = "_"
    ctr = 0
    alphabet_idx = -1

    for ev in button_events():
        if ev == buttons.BOTTOM_RIGHT:
            # Scroll down
            alphabet_idx += 1
            alphabet_idx %= len(alphabet)
            cur_str = cur_str[:ctr] + alphabet[alphabet_idx]

        elif ev == buttons.BOTTOM_LEFT:
            # Scroll up
            alphabet_idx = alphabet_idx-1 if alphabet_idx > 0 else len(alphabet)-1
            cur_str = cur_str[:ctr] + alphabet[alphabet_idx]

        elif ev == buttons.TOP_RIGHT:
            ctr += 1
            if ctr == 10:
                cur_str = cur_str[:len(cur_str)-1] + " "
                break
            if alphabet_idx < 0:
                cur_str = cur_str[:len(cur_str)-1] + " "
            alphabet_idx = -1
            cur_str += "_"

        draw_menu(disp, cur_str)

    cur_str = cur_str.strip()

    while True:
        for k in range(4):
            (x1, y1) = (rand()%159, rand()%79)
            (x2, y2) = (min(x1+rand()%40, 159), min(y1+rand()%40, 79))
            try:
                disp.rect(x1, y1, x2, y2, col=colors[rand() % len(colors)], filled=True)
            except:
                pass

        fg = colors[rand()%len(colors)]
        nx = 80-round(len(cur_str)/2 * 14)

        disp.print(cur_str, fg=fg, bg=[0xff-c for c in fg], posx=(nx-8)+rand()%16, posy=22+rand()%16)
        disp.update()

        leds.set(rand() % 11, colors[rand() % len(colors)])
        leds.set_rocket(rand() % 3, rand() % 32)
        utime.sleep_us(1) # Feed watch doge

if __name__ == "__main__":
    main()