"""
Movalite by The Dod:
Adafruit CircuitPlayground Bluefruit motion-sensitiuve "bling"
The RGB levels of neopixels around the circuit are affected
by X/Y/Z acceleration

Controls:
    slider switch: normal/standby mode
    button a: increase brightness
    button b: decrease brightness
"""
import math
import time
from adafruit_circuitplayground import cp

NUM_PIXELS = 10
# Like a clock, with connectors at 12 (USB) and 6 (power)
LED_ANGLES = [
    i*math.pi/6.0
    for i in [11, 10, 9, 8, 7, 5, 4, 3, 2, 1]]

minx = miny = minz = -5.0
maxx = maxy = maxz = 5.0

cp.pixels.brightness = 0.1

is_standby = cp.switch
last_click = 0
DEBOUNCE = 0.25

def angles2level(led, val):
    led_angle = LED_ANGLES[led]
    val_angle = val * 2.0 * math.pi
    angle = led_angle - val_angle
    while angle > 2 * math.pi:
        angle -= 2*math.pi
    # the pow() makes sin() values sharper
    return int(255*pow(math.sin(angle/2), 4))

while True:
    if time.monotonic() > last_click+DEBOUNCE:
        if is_standby != cp.switch:
            is_standby = cp.switch
            last_click = time.monotonic()
            if is_standby:
                for i in range(NUM_PIXELS):
                    cp.pixels[i] = (0, 0, 0)
        if cp.button_b:
            last_click = time.monotonic()
            cp.pixels.brightness = max(0.05, cp.pixels.brightness*0.9)
        elif cp.button_a:
            last_click = time.monotonic()
            cp.pixels.brightness = min(0.95, 1.0-(1.0-cp.pixels.brightness)*0.9)
    if not is_standby:
        x, y, z = cp.acceleration
        if x < minx:
            minx = x
        if y < miny:
            miny = y
        if z < minz:
            minz = z
        if x > maxx:
            maxx = x
        if y > maxy:
            maxy = y
        if z > maxz:
            maxz = z
        vals = (
            (x-minx)/(maxx-minx),
            (y-miny)/(maxy-miny),
            (z-minz)/(maxz-minz))
        for i in range(NUM_PIXELS):
            cp.pixels[i] = (
                angles2level(i, vals[0]),
                angles2level(i, vals[1]),
                angles2level(i, vals[2]))
    time.sleep(0.01)