# import libraries
import board, neopixel, time, adafruit_mcp9808, random, touchio, adafruit_lis3dh, busio, digitalio
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService
from adafruit_led_animation.color import RED, YELLOW, ORANGE, GREEN, TEAL, CYAN, BLUE, PURPLE, MAGENTA, GOLD, PINK, \
    AQUA, JADE, AMBER, OLD_LACE, WHITE, BLACK
from adafruit_led_animation.animation.rainbowcomet import RainbowComet

# setup bluetooth
ble = BLERadio()
uart_server = UARTService()
advertisement = ProvideServicesAdvertisement(uart_server)
# Set a unique name for the Bluetooth device
advertisement.complete_name = "Scarf"  # or try "ScarfTest" if issues persist
ble.name = advertisement.complete_name
# Start advertising
ble.start_advertising(advertisement)
print("Advertising started.")  # Debugging line to check if advertising started


# set up lights
led_pin = board.A1
num_leds = 16 # change based on the number of LEDs that fit in your scarf
pixels = neopixel.NeoPixel(led_pin,num_leds, brightness = 0.7, auto_write=False)
led_active = 0

# for non-BLE, set up mode buttons
touchpad_A2 = touchio.TouchIn(board.A2)
touchpad_A3 = touchio.TouchIn(board.A3)
touchpad_TX = touchio.TouchIn(board.TX)

# auto-off mode
def stop_leds():
    pixels.fill(BLACK)
    pixels.show()
    print("LED lighting stopped.")

# clear LEDs
def clear_leds():
    pixels.fill(BLACK)
    pixels.show()

# random lights mode
# List of colors to choose from
colors = [RED, YELLOW, ORANGE, GREEN, TEAL, CYAN, BLUE, PURPLE, MAGENTA, GOLD, PINK, AQUA, JADE, AMBER, OLD_LACE, WHITE, BLACK]
# Variables to keep track of previous light and color
prev_light = -1
prev_color = None
def get_random_color():
    # get a random color from the list, ensuring it's not a repeat color
    global prev_color
    new_color = random.choice(colors)
    while new_color == prev_color:
        new_color = random.choice(colors)
    prev_color = new_color
    return new_color
def get_random_light():
    # Get a random light index, ensuring it's not a repeat light
    global prev_light
    new_light = random.randint(0, num_leds - 1)
    while new_light == prev_light:
        new_light = random.randint(0, num_leds - 1)
    prev_light = new_light
    return new_light
def update_pixel():
    # set a random light to a random color
    light = get_random_light()
    color = get_random_color()
    # Turn on the light with a random color
    pixels[light] = color
    pixels.show()
    # Wait a bit to show the light on
    time.sleep(0.5)
    # Turn off the light (set to black)
    pixels[light] = BLACK
    pixels.show()

# Set up shake mode
i2c_acc = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA)
int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT)
accelerometer = adafruit_lis3dh.LIS3DH_I2C(i2c_acc, address=0x19, int1=int1)
accelerometer.range = adafruit_lis3dh.RANGE_8_G
rainbow_comet = RainbowComet(pixels, speed=0.1, tail_length=7, bounce=True)

# temp mode
# set up temp sensor
i2c_temp = board.I2C()
temp_sensor = adafruit_mcp9808.MCP9808(i2c_temp)
def get_temperature():
    # Get the temperature in Celsius and convert to Fahrenheit
    return temp_sensor.temperature * 9 / 5 + 32
def temp_change_lights():
    for i in range(num_leds):
        # Check if touchpad_TX is touched or if led_active is 0
        if touchpad_TX.value or led_active == 0:
            pixels.fill(BLACK)  # Turn off all LEDs immediately
            pixels.show()
            print("LED stopped due to TX touch or led_active == 0")
            return  # Exit the function and stop the loop
        # Take two temperature readings in Fahrenheit
        temp1 = get_temperature()
        time.sleep(0.5)  # Small delay to ensure we get a different reading
        temp2 = get_temperature()
        # Compare temperatures and light up the LED accordingly
        if temp1 > temp2:
            pixels[i] = PURPLE
        elif temp1 == temp2:
            pixels[i] = GREEN
        else:
            pixels[i] = RED
        pixels.show()
        time.sleep(0.25)  # Wait 0.25 seconds between readings
    # Once all LEDs are lit, turn them off
    pixels.fill(BLACK)  # Turn off all LEDs
    pixels.show()
    # Wait for a moment before repeating the process
    time.sleep(1)

print("Code is running")

while True:
    if touchpad_A2.value:  # If A2 is touched
        clear_leds()
        led_active = 1  # Set the LED active flag to True
        print("LED lighting activated via touchpad_A2.")
    if touchpad_A3.value:
        clear_leds()
        led_active = 2
    if accelerometer.shake(shake_threshold=12):
        clear_leds()
        led_active = 3
    if touchpad_TX.value:  # If TX is touched
        led_active = 0  # Set the LED active flag to False
        stop_leds()  # Immediately stop LED lighting
        print("LED lighting deactivated via touchpad_TX.")
        # Bluetooth UART communication - check for incoming data
    if uart_server.in_waiting:
        data = uart_server.read(1).decode("utf-8")  # Read a single character
        if data == '1':  # Activate LEDs via Bluefruit Connect
            clear_leds()
            led_active = 1
            print("LED lighting activated via Bluetooth.")
        if data == '2':
            clear_leds()
            led_active = 2
        if data == '3':
            clear_leds()
            led_active = 3
        elif data == '0':  # Deactivate LEDs via Bluefruit Connect
            led_active = 0
        # Run the LED lighting loop if LEDs are activated
    if led_active == 1:
        temp_change_lights()
    if led_active == 2:
        update_pixel()
    if led_active == 3:
        rainbow_comet.animate()
        pixels.show()
    if led_active == 0:
        stop_leds()
        print("LED lighting deactivated via Bluetooth.")
    time.sleep(0.1)  # Small delay to avoid overwhelming the system
