import ugfx, badge, random

badge.leds_enable()
ugfx.init()
ugfx.input_init()
ugfx.set_lut(ugfx.LUT_FULL)
ugfx.clear(ugfx.BLACK)
ugfx.flush()

scary = True
leds_en =True
colors = ((024, 008, 128, 0),
          (029, 002, 213, 0),
          (013, 071, 238, 0),
          (046, 038, 189, 0),
          (046, 038, 106, 0),
          (002, 065, 205, 0),
          (027, 213, 169, 0),
          (016, 149, 092, 0),
          (034, 169, 194, 0),
          (018, 210, 191, 0),
          (064, 031, 245, 0))

def lerp(t: float, a: (int,), b: (int,)):
    if len(a) != len(b):
        raise AttributeError("The two tuples must be the same length")
    elif t > 1 or t < 0:
        raise AttributeError("The interp parameter must be between 0 and 1")
    else:
        diff_v = (b_i - a_i for a_i, b_i in zip(a, b))
        return tuple((a_i + v_i * t for a_i, v_i in zip(a, diff_v)))


def toggle_scary(pushed):
    global scary
    if pushed:
        scary = not scary

def toggle_leds(pushed):
    global leds_en
    if pushed:
        leds_en = not leds_en
        if leds_en:
            badge.leds_enable()
        else:
            badge.leds_disable()

def go_home(pushed):
    if pushed:
        badge.leds_send_data(bytes([0] * 24))
        badge.leds_disable()
        ugfx.set_lut(ugfx.LUT_FULL)
        ugfx.clear(ugfx.BLACK)
        ugfx.flush()
        ugfx.clear(ugfx.WHITE)
        ugfx.flush()
        import machine
        machine.deepsleep(1)

ugfx.input_attach(ugfx.BTN_A, toggle_scary)
ugfx.input_attach(ugfx.BTN_B, toggle_leds)
ugfx.input_attach(ugfx.BTN_START, go_home)
ugfx.orientation(90)
w, h, _, _ = badge.png_info('/lib/lain/lain-0.png')
w_tot, h_tot = ugfx.width(), ugfx.height()
ugfx.set_lut(ugfx.LUT_FASTEST)
idx = 0
leds = ((0,) * 4,) * 6
while True:
    badge.eink_busy_wait()
    if not idx:
        ugfx.set_lut(ugfx.LUT_NORMAL)
        ugfx.string_box(0, 0, w_tot - 10, int(h_tot * 0.35),
                        "Let's all love Lain!",
                        "Roboto_Black22", ugfx.WHITE, ugfx.justifyLeft)
        ugfx.set_lut(ugfx.LUT_FASTEST)
        leds_old = leds
        leds = tuple((random.choice(colors) for _ in range(6)))
    badge.eink_png(h_tot - w, -5, '/lib/lain/lain-{}.png'.format(idx))
    if leds_en:
        badge.leds_send_data(bytes((int(byte)
                                    for led, led_o in zip(leds, leds_old)
                                    for byte in lerp(idx / 24, led_o, led))))
    if scary and not (idx % 3):
        ugfx.flush()
        badge.eink_png(h_tot - w, -5, '/lib/lain/lain-eye.png')

    ugfx.flush()
    idx = (idx + 1) % 24


# ugfx.flush()
