import time
import board
import pwmio
from adafruit_motor import servo
import neopixel
import digitalio
from audiopwmio import PWMAudioOut as AudioOut
from audiocore import WaveFile

speaker = digitalio.DigitalInOut(board.SPEAKER_ENABLE)
speaker.direction = digitalio.Direction.OUTPUT # Set up the speaker as an output
speaker.value = True
audio = AudioOut(board.AUDIO)

button = digitalio.DigitalInOut(board.A5) # This line is essentially the same as the CPB button
button.switch_to_input(pull=digitalio.Pull.UP) # However, the external button uses Pull.UP instead of Pull.DOWN

strip_pin = board.A6
strip_number_of_lights = 30

strip = neopixel.NeoPixel(strip_pin, strip_number_of_lights, brightness = 1.0, auto_write = True)

pwm_1 = pwmio.PWMOut(board.A1, frequency=50)
servo_1 = servo.Servo(pwm_1, min_pulse=750, max_pulse=2200)

pwm_2 = pwmio.PWMOut(board.A2, frequency=50)
servo_2 = servo.Servo(pwm_2, min_pulse=750, max_pulse=2200)


#colors
MAROON = (128,0,0)
GOLD = (255, 215, 0)

servo_1.angle = 90
servo_2.angle = 90
servo_direction = 'decreasing'

def servo_move():
    global servo_direction
    if round(servo_1.angle) == 80 or round(servo_1.angle) == 100:
        servo_1.angle = 90
        servo_2.angle = 90
        if servo_direction == 'increasing':
            servo_direction = 'decreasing'
        else:
            servo_direction = 'increasing'
    elif servo_direction == 'increasing':
        servo_1.angle = 100
        servo_2.angle = 100
    elif servo_direction == 'decreasing':
        servo_1.angle = 80
        servo_2.angle = 80
    print(round(servo_1.angle), servo_direction)

def lightshow():
    global servo_direction

    for light in range(len(strip)):
        if light % 2 == 0:
            strip[light] = GOLD
        else:
            strip[light] = MAROON

    servo_move()
    time.sleep(.05)

    for light in range(len(strip)):
        if light % 2 == 0:
            strip[light] = MAROON
        else:
            strip[light] = GOLD

    servo_move()
    time.sleep(.05)


path = "sounds/"
def play_file(filename):
    with open(path + filename, "rb") as wave_file:
        wave = WaveFile(wave_file)
        audio.play(wave)
        while audio.playing:
            lightshow()

strip.fill((0,0,0))

while True:
    if button.value: # Flipped from the on board button. If button.value is True, the button is OFF!
        continue
    else:
        print("button")
        play_file('for-boston.wav')
        strip.fill((0,0,0))
        servo_1.angle = 90
        servo_2.angle = 90









