import vibra
import utime
import leds
import personal_state
import buttons
import display


_rand = 123456789
def rand():
    global _rand
    _rand = (1103515245 * _rand + 12345) & 0xffffff
    return _rand

def vibra_alarm(times=1):
    for i in range(times):
        # Turn on vibration motor for 60 ms
        vibra.vibrate(60)
        utime.sleep_ms(120)

gs = 60
colors = [ ((i>>2)*gs, (i>>1&1)*gs, (i&1)*gs) for i in range(1, 8) ]
gs = 80
pink_color = [
    (int(2 * gs), gs, gs),
    (int(1.75 * gs), int(0.8 * gs), int(0.8 * gs)),
    (int(1.6 * gs), int(0.5 * gs), int(0.5 * gs)),
    (int(1.2 * gs), int(0.5 * gs), int(0.5 * gs)),
    (int(1.3 * gs), int(0.5 * gs), int(0.5 * gs)),
    (int(1.75 * gs), int(0.8 * gs), int(0.8 * gs)),
]

RED = (255, 0, 0)

# dimensionen: (28, 20)
def draw_herz(disp, x, y):
    disp.line (x     , y     , x + 10, y + 10, col=RED, size=8)
    disp.line (x + 20, y     , x + 10, y + 10, col=RED, size=8)
    disp.line (x     , y +  9, x + 10, y + 19, col=RED, size=2)
    disp.line (x + 20, y +  9, x + 10, y + 19, col=RED, size=2)
    disp.pixel(x + 10, y + 20                , col=RED)

# persist: True
personal_state.set(personal_state.COMMUNICATION, True)

with display.open() as disp:
    disp.clear(col=pink_color[0])
    disp.print("use buttons to find:    love ;)", posy=10)
    disp.update()

for j in range(15):
    leds.set(j, pink_color[0])

utime.sleep_ms(1024)

# wie viele Runden pink anzeigen?
pink = 0

#herz_bmp = read_bitmap("apps/amore/herz.bmp")

i = 0
while True:
    if pink > 1:
        pink -= 1
        for j in range(15):
            leds.set(j, pink_color[(j+i) % len(pink_color)])

        with display.open() as disp:
            disp.clear(col=(42, 42, 42))

            draw_herz(disp,   5, (pink +  0) % 60)
            draw_herz(disp,  33, (pink + 40) % 60)
            draw_herz(disp,  66, (pink + 20) % 60)
            draw_herz(disp,  99, (pink + 10) % 60)
            draw_herz(disp, 132, (pink + 30) % 60)

            disp.update()
    elif pink == 1:
        pink -= 1
        vibra_alarm(1)
        with display.open() as disp:
            disp.clear(col=(0, 0, 0))
            disp.update()
            disp.backlight(0)
    else:
        leds.set(rand() % 11, colors[rand() % len(colors)])


    if i < 64:
        i += 1
    else:
        i = 0
        leds.set_rocket(rand() % 3, rand() % 32)
        pressed = buttons.read(
            buttons.BOTTOM_LEFT | buttons.BOTTOM_RIGHT
        )
        if pressed & buttons.BOTTOM_RIGHT != 0:
            pink = 64
            vibra_alarm(2)
        if pressed & buttons.BOTTOM_LEFT != 0:
            pink = 1024
            vibra_alarm(3)
        if pink > 0:
            with display.open() as disp:
                disp.backlight(40)

    utime.sleep_us(1) # Feed watch doge