

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)
advertisement.complete_name = "chris-k"
ble.name = advertisement.complete_name



# SET UP THE 10 NEOPIXELS ON THE CPB. NAME THEM PIXELS
pixels = neopixel.NeoPixel(board.NEOPIXEL, 10)
strip = neopixel.NeoPixel(board.A1, 30, brightness = 0.0)

# SET UP COLORS & A COLORS LIST
RED = (255, 0, 0)
MAGENTA = (255, 0, 20)
ORANGE = (255, 40, 0)
YELLOW = (255, 150, 0)
GREEN = (0, 255, 0)
JADE = (0, 255, 40)
BLUE = (0, 0, 255)
INDIGO = (63, 0, 255)
VIOLET = (127, 0, 255)
PURPLE = (180, 0, 255)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

# CREATE AN ARRAY OF THESE COLORS
colors = [RED, MAGENTA, ORANGE, YELLOW, GREEN, JADE, BLUE, INDIGO, VIOLET, PURPLE, WHITE, BLACK]
colorReceived = False

# These are the ButtonPacket codes that are the same as the 8 buttons on the Bluefruit App
bluefruit_buttons = [ButtonPacket.BUTTON_1, ButtonPacket.BUTTON_2, ButtonPacket.BUTTON_3,
            ButtonPacket.BUTTON_4, ButtonPacket.UP, ButtonPacket.DOWN,
            ButtonPacket.LEFT, ButtonPacket.RIGHT]


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:
            print("Connected") # If BLE is connected...
            was_connected = True
            if uart.in_waiting:
                print("In Waiting")
                try:
                    packet = Packet.from_stream(uart)  # Create the packet object.
                except ValueError:
                    continue
                if isinstance(packet, ColorPacket):
                    print("Packet Received")
                    strip.fill(packet.color)
                    colorReceived = True
                    if packet.color == BLACK:
                        colorReceived = False
                        break
            if colorReceived:
                for i in range(0,101):
                    strip.brightness = i/100
                    time.sleep(0.01)
                time.sleep(0.5)
                for i in range(100,-1,-1):
                    strip.brightness = i/100
                    time.sleep(0.01)


