# SPDX-FileCopyrightText: 2023 Anne Barela and Amy Lendian
#
# SPDX-License-Identifier: MIT

import board
import neopixel
import digitalio
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

ble = BLERadio()
uart = UARTService()
advertisement = ProvideServicesAdvertisement(uart)

contact = digitalio.DigitalInOut(board.TX)
contact.direction = digitalio.Direction.OUTPUT
contact.value = False

pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=0.2)
pixels[0] = (0, 0, 0)
pixels[9] = (0, 0, 0)

while True:
    ble.start_advertising(advertisement)
    while not ble.connected:
        pixels[9] = (0, 0, 0)
        pass

    # Now we're connected

    while ble.connected:
        pixels[9] = (0, 255, 0)
        if uart.in_waiting:
            packet = Packet.from_stream(uart)
            if isinstance(packet, ButtonPacket):
                if packet.pressed:
                    if packet.button == ButtonPacket.BUTTON_1:
                        # The 1 button was pressed.
                        print("1 button pressed!")
                    elif packet.button == ButtonPacket.UP:
                        # The UP button was pressed.
                        print("UP button pressed!")
                        contact.value = True
                        pixels[0] = (0, 0, 255)
                    elif packet.button == ButtonPacket.DOWN:
                        # The DOWN button was pressed
                        print("DOWN button pressed!")
                        contact.value = False
                        pixels [0] = (0, 0, 0)

    # If we got here, we lost the connection. Go up to the top and start
    # advertising again and waiting for a connection.