# PiLi.py by Liang in CCCamp 2019

# Automatically turned on when it's dark ;)

# Buttons on the right adjust blink speed

import display, light_sensor, color, leds, buttons, power
import utime, urandom

FADE_LIMIT = 50
HUE_STEP = 101
PULSE_TIME = 0
SLEEP_TIME = 0
hue = 0
led_color = 0
batt = 0
button_state = 0
light_sensor.start()
disp = display.open()
leds.set_powersave(True)
leds.clear()
disp.clear()
disp.update()

while True:

    leds.clear()
    utime.sleep_ms(PULSE_TIME)
    uran = urandom.randint(0,14)
    batt = round(power.read_battery_voltage(),2)
    sensor_value = light_sensor.get_reading()
    hue = (hue + HUE_STEP)%360
    led_color = color.from_hsv(hue, 1, 1)

    if batt < 3.53:
        disp.print("Charge Me!",posx=10, posy=30)
        disp.update()
    
    if sensor_value < FADE_LIMIT:

        pressed = buttons.read(buttons.TOP_RIGHT | buttons.BOTTOM_RIGHT | buttons.BOTTOM_LEFT)

        if pressed & buttons.TOP_RIGHT != 0:
            SLEEP_TIME = SLEEP_TIME + 1

        if pressed & buttons.BOTTOM_RIGHT != 0:
            SLEEP_TIME = SLEEP_TIME - 1 

        if pressed & buttons.BOTTOM_LEFT != 0:
            button_state = ~button_state
            utime.sleep(0.2)

        if SLEEP_TIME < 1:
            SLEEP_TIME = 1

        PULSE_TIME = SLEEP_TIME

        if button_state != 0 :
            leds.clear()
            pass      
        else:
            leds.set(uran,led_color)
        
        brightness = 20
     
    else:
        leds.clear()
        disp.clear()
        brightness = urandom.randint(0,40)
        PULSE_TIME = sensor_value - FADE_LIMIT

    x = urandom.randint(0,160)
    y = urandom.randint(0,80)
    rad = urandom.randint(1, 25)
    
    disp.backlight(brightness)
    disp.circ(x, y, rad, col = led_color, filled = True, size = 1)
    disp.update()
    
    utime.sleep_ms(PULSE_TIME)