import buttons
import display
import ledfx
import leds
import math

# Play with these to change your rainbow!
hue_radius = 360
speed_multiplier = 4  # Divide by this value to get hte speed the animation plays.
screen_rects = 20  # How many rectangles to use for the screen rainbow

# 0 - 11: Front
# 12 - 15: Halo
led_count = 11
base_led_count = 4
screen_width = 159
screen_height = 79

rect_width = int(math.ceil(160/screen_rects))

def hsv_2_rgb(hsv):
    h,s,v = hsv
    h = float(h)
    s = float(s)
    v = float(v)
    h60 = h / 60.0
    h60_floor = math.floor(h60)
    hi = int(h60_floor) % 6
    f = h60 - h60_floor
    p = v * (1 - s)
    q = v * (1 - f * s)
    t = v * (1 - (1 - f) * s)
    r, g, b = 0, 0, 0
    if hi == 0: r, g, b = v, t, p
    elif hi == 1: r, g, b = q, v, p
    elif hi == 2: r, g, b = p, v, t
    elif hi == 3: r, g, b = p, q, v
    elif hi == 4: r, g, b = t, p, v
    elif hi == 5: r, g, b = v, p, q
    r, g, b = int(r * 255), int(g * 255), int(b * 255)
    return r, g, b

def hue(h):
    return (h % 360, 1, 1)

with display.open() as disp:
    disp.clear().update()

    t = 0.0
    last_pressed = 0
    while True:
        t += speed_multiplier
        outputs = []
        for led in range(led_count):
            outputs.append(hue(int(t) + led * (hue_radius / led_count)))
        for led in range(base_led_count):
            outputs.append(hue(int(t) + led * (hue_radius / base_led_count)))
        leds.set_all_hsv(outputs)
        for r in range(screen_rects):
            disp.rect(
                r * rect_width, 0,
                min((r + 1) * rect_width, screen_width), screen_height,
                col=hsv_2_rgb(
                    hue(int(-t) + r * (hue_radius / screen_rects))))
        disp.update()
        pressed = buttons.read(buttons.BOTTOM_RIGHT | buttons.TOP_RIGHT)
        if last_pressed != pressed:
            last_pressed = pressed
            if pressed == buttons.TOP_RIGHT:
                speed_multiplier += 1
            if pressed == buttons.BOTTOM_RIGHT:
                speed_multiplier -= 1