import board, neopixel, 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.button_packet import ButtonPacket

# Setup Bluetooth
ble = BLERadio()
uart_server = UARTService()
advertisement = ProvideServicesAdvertisement(uart_server)
advertisement.complete_name = "NJW CPB"
ble.name = advertisement.complete_name  # Makes it show in Bluefruit Connect app
print(f"ble.name is {ble.name}")

# Define colors
RED = (100, 0, 0)
BLUE = (0, 0, 100)
YELLOW = (100, 50, 0)
BLACK = (0, 0, 0)  # Used to turn LEDs off

# LED Strip setup
led_pin = board.A1
num_leds = 30
strip = neopixel.NeoPixel(led_pin, num_leds, brightness=1, auto_write=False)
strip.fill(BLACK)
strip.show()

print("Sports Team Wall Art is Running!")

while True:
    ble.start_advertising(advertisement)
    while not ble.connected:
        pass  # Wait for a connection

    ble.stop_advertising()

    while ble.connected:
        if uart_server.in_waiting:
            try:
                packet = Packet.from_stream(uart_server)
            except ValueError:
                continue  # Ignore invalid packets

            if isinstance(packet, ButtonPacket) and packet.pressed:
                strip.fill(BLACK)  # Turn off all LEDs before updating

                if packet.button == ButtonPacket.BUTTON_1:  # Lights 1-10 RED
                    print("*** LIGHTING UP LEDs 1-10 in RED ***")
                    for i in range(10):
                        strip[i] = RED
                elif packet.button == ButtonPacket.BUTTON_2:  # Lights 11-20 BLUE
                    print("*** LIGHTING UP LEDs 11-20 in BLUE ***")
                    for i in range(10, 20):
                        strip[i] = BLUE
                elif packet.button == ButtonPacket.BUTTON_3:  # Lights 21-30 YELLOW
                    print("*** LIGHTING UP LEDs 21-30 in YELLOW ***")
                    for i in range(20, 30):
                        strip[i] = YELLOW

                strip.show()  # Apply changes


