import board, neopixel
from adafruit_led_animation.animation.pulse import Pulse
import adafruit_vl53l1x
import time
import microcontroller
from audiomp3 import MP3Decoder
from audiopwmio import PWMAudioOut as AudioOut
import random
from adafruit_led_animation.color import (
    AMBER, #(255, 100, 0)
    AQUA, # (50, 255, 255)
    BLACK, #OFF (0, 0, 0)
    BLUE, # (0, 0, 255)
    CYAN, # (0, 255, 255)
    GOLD, # (255, 222, 30)
    GREEN, # (0, 255, 0)
    JADE, # (0, 255, 40)
    MAGENTA, #(255, 0, 20)
    OLD_LACE, # (253, 245, 230)
    ORANGE, # (255, 40, 0)
    PINK, # (242, 90, 255)
    PURPLE, # (180, 0, 255)
    RED, # (255, 0, 0)
    TEAL, # (0, 255, 120)
    WHITE, # (255, 255, 255)
    YELLOW)

colors = [RED, MAGENTA, ORANGE, YELLOW, GREEN, JADE, TEAL, BLUE, PINK, PURPLE, WHITE]

audio = AudioOut(board.GP16)
# set path to the folder where the sound files can be found on the device, example below is for a folder named alarm
path = "mp3s/"
# set up the mp3 decoder
filename = "sound2.mp3" # change to valid file in your path
mp3_file = open(path + filename, "rb")
decoder = MP3Decoder(mp3_file)
# Call this function passing in a String for the full filename with extension.
def play_mp3(filename):
    decoder.file = open(path + filename, "rb")
    audio.play(decoder)
    while audio.playing:
        pulse() # add code here that you want to run while sound plays

green = (0,255,0)

i2c = board.STEMMA_I2C()

pixels = neopixel.NeoPixel(board.GP28, 40, brightness = 0.5, auto_write=True)

pulse_strip = Pulse(pixels, speed=0.01, color=green, period=1)

distance_sensor = adafruit_vl53l1x.VL53L1X(i2c)
distance_sensor.distance_mode = 1
distance_sensor.timing_budget = 100
distance_sensor.start_ranging()

counter = 0
pixels.fill((0,0,0))

def find_distance(dist_inp):
    if type(dist_inp) != float:
        dist_inp = 10000
    return dist_inp

def pulse():
    for i in range(20):
        pixels[i] = colors[random.randint(0,len(colors)-1)]
    pixels.show()
    for i in range(100):
        pixels.brightness = i/100
        pixels.show()
        time.sleep(0.0005)
    for i in reversed(range(100)):
        pixels.brightness = i/100
        pixels.show()
        time.sleep(0.0005)

pixels.fill((0,0,0))
pixels.show()

loop_len = 2

loops_left = 0
while True:
    pixels.fill((0,0,0))
    pixels.show()
    pixels.brightness = 0.0
    distance = find_distance(distance_sensor.distance)
    if distance < 30.00:
        loops_left = loop_len
    while loops_left > 0:
        play_mp3(filename)
        loops_left -= 1
