import board
import neopixel
import time
import random
import digitalio
import adafruit_lis3dh

import busio

# imports needed for bluetooth
from digitalio import DigitalInOut, Direction, Pull
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

# import animations and colors
# While we don't use all of these animations and colors
# I import them all below in case you want to experiment with them.
# Full documentation for the adafruit_led_animation library is at:
# https://circuitpython.readthedocs.io/projects/led-animation/en/latest/api.html
import adafruit_led_animation
from adafruit_led_animation.animation.solid import Solid
from adafruit_led_animation.animation.colorcycle import ColorCycle
from adafruit_led_animation.animation.blink import Blink
from adafruit_led_animation.animation.comet import Comet
from adafruit_led_animation.animation.chase import Chase
from adafruit_led_animation.animation.pulse import Pulse
from adafruit_led_animation.animation.rainbow import Rainbow
from adafruit_led_animation.animation.rainbowChase import RainbowChase
from adafruit_led_animation.animation.rainbowcomet import RainbowComet
from adafruit_led_animation.animation.rainbowsparkle import RainbowSparkle
from adafruit_led_animation.animation.sparkle import Sparkle
from adafruit_led_animation.animation.SparklePulse import SparklePulse
from adafruit_led_animation.sequence import AnimationSequence
from adafruit_led_animation.sequence import AnimateOnce
from adafruit_led_animation.color import (
    AMBER, #(255, 100, 0)
    AQUA, # (50, 255, 255)
    BLACK, #OFF (0, 0, 0)
    BLUE, # (0, 0, 255)
    CYAN, # (0, 255, 255)
    GOLD, # (255, 222, 30)
    GREEN, # (0, 255, 0)
    JADE, # (0, 255, 40)
    MAGENTA, #(255, 0, 20)
    OLD_LACE, # (253, 245, 230)
    ORANGE, # (255, 40, 0)
    PINK, # (242, 90, 255)
    PURPLE, # (180, 0, 255)
    RED, # (255, 0, 0)
    TEAL, # (0, 255, 120)
    WHITE, # (255, 255, 255)
    YELLOW, # (255, 150, 0)
    RAINBOW # a list of colors to cycle through
    # RAINBOW is RED, ORANGE, YELLOW, GREEN, BLUE, and PURPLE ((255, 0, 0), (255, 40, 0), (255, 150, 0), (0, 255, 0), (0, 0, 255), (180, 0, 255))
)
INDIGO =(63,0,255)
VIOLET = (127,0,255)



# setup bluetooth
ble = BLERadio()
uart_server = UARTService()
advertisement = ProvideServicesAdvertisement(uart_server)
# Give your CPB a unique name between the quotes below
advertisement.complete_name = "LED-Sign"

runAnimation = False
animation_number = -1
lightPosition = -1

# Update to match the pin connected to your NeoPixels
led_pin = board.A1
# UPDATE NUMBER BELOW to match the number of NeoPixels you have connected
num_leds = 20
# UPDATE color below if you want your light to show a different color at startup
defaultColor = AQUA
pickedColor = defaultColor

# I've programmed these values to set, then adjust the timing of animations
defaultTime = 0.1
minWaitTime = 0.01
hundredths = 0.01
tenths = 0.1
adjustedTime = defaultTime

# Sets up the Neopixel strand,initializing it to full brightness
strip = neopixel.NeoPixel(board.A1, 6, brightness = 0.5, auto_write = True)

#set up accelerometer
i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA)
int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT)
accelerometer = adafruit_lis3dh.LIS3DH_I2C(i2c,address = 0x19, int1=int1)
accelerometer.range = adafruit_lis3dh.RANGE_8_G


# Set LEDs to light up sold in the default color
strip.fill(pickedColor)
strip.write()

#set up for the code below in the while true loop

last_random = -1

strip_len = [0,1,2,3,4,5]
lights = False
count = 0
colors = [RED,ORANGE,YELLOW, GREEN,BLUE, VIOLET]

times = 0
steps = 0

button_4_pressed = True

while True:
    ble.start_advertising(advertisement)
    while not ble.connected:
        if runAnimation == True:
            runSelectedAnimation()


    ble.stop_advertising()

    while ble.connected:
        if uart_server.in_waiting:
            try:
                packet = Packet.from_stream(uart_server)
            except ValueError:
                continue # or pass. This will start the next

            if isinstance(packet, ColorPacket):
                print("*** color sent")
                print("pickedColor = ", ColorPacket)
                runAnimation = False
                animation_number = 0
                strip.fill(packet.color)
                strip.write()
                pickedColor = packet.color
                # the // below will drop any remainder so the values remain Ints, which color needs
                fade_color = (pickedColor[0]//2, pickedColor[1]//2, pickedColor[2]//2)
                # reset light_position after picking a color
                light_position = -1

            if isinstance(packet, ButtonPacket):
                if packet.pressed:
                    if packet.button == ButtonPacket.BUTTON_1:
                        rotation = 0
                        while True:
                            if rotation <= 50:
                                random_number = random.randint(0,5)
                                while last_random == random_number:
                                    random_number = random.randint(0,5)
                                strip[random_number] = AQUA
                                time.sleep(0.1)
                                strip[random_number]= BLACK
                                last_random = random_number
                                rotation +=1

                            else:
                                print("one is pressed")
                                strip.fill(BLACK)
                                break


                    elif packet.button == ButtonPacket.BUTTON_2:
                        strip.fill(AQUA)
                        print("Two pressed")
                    elif packet.button == ButtonPacket.BUTTON_3:
                        print("button three pressed")
                        if lights == False:
                            for index in range(len(strip)):
                                strip[index]=(colors[index])
                                time.sleep(0.2)
                            for index in (range(5,0,-1)):
                                strip[index]= BLACK
                                time.sleep(0.2)
                            lights = True
                            strip.fill(BLACK)
                            lights = False

                    elif packet.button == ButtonPacket.BUTTON_4:
                        x,y,z = accelerometer.acceleration
                        print("*** Button 4 Was Pressed ****")
#                         times = 0
#                         count = 0
                        while button_4_pressed == True:
                            x,y,z = accelerometer.acceleration
                            if steps <= 100 and z >= 20:
                                print("Step2")
                                strip.fill(GREEN)
                                steps += 1
                                strip.fill(BLACK)
                            elif steps >= 100 and z >= 20:
                                steps += 1
                                strip.fill(RED)
                            elif steps >= 110:
                                break
                            else:
                                print("Button 4 pressed")
                                strip.fill(BLACK)

