import board, neopixel, digitalio, time
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

from adafruit_bluefruit_connect.packet import Packet
from adafruit_bluefruit_connect.color_packet import ColorPacket
from adafruit_bluefruit_connect.button_packet import ButtonPacket
from adafruit_bluefruit_connect.raw_text_packet import RawTextPacket


# Setup BLE connection
ble = BLERadio()
uart = UARTService()
advertisement = ProvideServicesAdvertisement(uart)
# Give your CPB a unique name between the quotes below.
# This MUST be the same name - same spelling & capitalization
# as the name in the "receiver_name = " line in the SENDER's code.py file.
# VERY IMPORTANT - the name must also be <= 11 characters!
advertisement.complete_name = "chris-k"
ble.name = advertisement.complete_name

strip = neopixel.NeoPixel(board.A1, 30)

from audiopwmio import PWMAudioOut as AudioOut
from audiocore import WaveFile

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

# set path where sound files can be found
path = "sounds/"

# to play a sound, call the play_sound function & pass in a
# filename as a string. Be sure to include the extension, e.g. "splat.wav")
def play_sound(filename):
    with open(path + filename, "rb") as wave_file:
        wave = WaveFile(wave_file)
        audio.play(wave)
        while audio.playing:
            pass

while True:
    ble.start_advertising(advertisement)  # Start advertising.
    print(f"Advertising as: {advertisement.complete_name}") # Name prints once each time the board isn't connected
    was_connected = False

    while not was_connected or ble.connected:
        if ble.connected: # If BLE is connected...
            was_connected = True
            if uart.in_waiting:  # Check to see if any new data has been sent from the SENDER.
                try:
                    packet = Packet.from_stream(uart)  # Create the packet object.
                except ValueError:
                    continue
                # Note: I could have sennt ColorPackets that would have had colors, but I wanted
                # to show ButtonPackets because you could do non-color things here, too. For example,
                # if Button_1, then move a servo, if Button_2, then play a certain sound, etc.
                if isinstance(packet, RawTextPacket):
                    print(f"Message Received: {packet.text.decode().strip()}")
                    sent_message = packet.text.decode().strip()
                    if sent_message == "play":
                        strip.fill((255,0,0))
                        play_sound("GoalHorn.wav")
                        strip.fill((0,0,0))


