import analogio
import board, neopixel, time, adafruit_vl53l1x, math, digitalio

from audiocore import WaveFile
try:
    from audioio import AudioOut
except ImportError:
    try:
        from audiopwmio import PWMAudioOut as AudioOut
    except ImportError:
        print("This board does not support audio")

pixels = neopixel.NeoPixel(board.NEOPIXEL, 10)
RED = (255,0,0)
BLACK = (0,0,0)
BLUE = (0,0,255)

strip = neopixel.NeoPixel(board.A1, 30)

print("Program is running")

speaker = digitalio.DigitalInOut(board.SPEAKER_ENABLE)
speaker.direction = digitalio.Direction.OUTPUT
speaker.value = True

audio = AudioOut(board.SPEAKER)

light_sensor = analogio.AnalogIn(board.LIGHT)

path = "alarm/"

def play_sound(filename):
    with open(path + filename, "rb") as wave_file:
        wave = WaveFile(wave_file)
        audio.play(wave)
        while audio.playing:
            red_pulse()

def red_pulse():
    pixels.fill(RED)
    strip.fill(RED)
    for i in range(0, 101):
        pixels.brightness = i/100
    for i in range(100, -1, -1):
        pixels.brightness = i/100

def blue_pulse():
    strip.fill(BLUE)
    pixels.fill(BLUE)
    for i in range(99, 101):
        pixels.brightness = i/100
    for i in range(100, 99, -1):
        pixels.brightness = i/100

start_playing = False
pixels.brightness = 0


# Prior video also shows setup code changes for Raspberry Pi Pico & QT Py RP2040
i2c = board.I2C()
distance_sensor = adafruit_vl53l1x.VL53L1X(i2c)
distance_sensor.distance_mode = 1

distance_sensor.timing_budget = 200

distance_sensor.start_ranging()

MAX_DISTANCE = 100 # was 150
MIN_DISTANCE = 10 # was 30

while True:
    if light_sensor.value < 10:
        print(light_sensor.value)
        #strip.fill(BLUE)
        blue_pulse()
        #time.sleep(.5)
    elif light_sensor.value >= 10:
        print(light_sensor.value)
        strip.fill(BLACK)
        pixels.fill(BLACK)
        #time.sleep(.5)
    if distance_sensor.data_ready:
        distance = distance_sensor.distance
        if distance == None: # do nothing if 0 reading, which shows up if nothing is in front of sensor
            continue # this skips the rest of the code & restarts the loop
        if distance < MAX_DISTANCE: # assume it's at max distance
            start_playing = True
        if start_playing:  # same as "if start_playing == True:"
            play_sound("siren.wav")
        time.sleep(2.0)