import board, time, pwmio, neopixel
import os, ssl, socketpool, wifi
import adafruit_minimqtt.adafruit_minimqtt as MQTT
from audiopwmio import PWMAudioOut as AudioOut
from audiomp3 import MP3Decoder
from adafruit_led_animation.color import RED, YELLOW, ORANGE, GREEN, TEAL, CYAN, BLUE, PURPLE, MAGENTA, \
    GOLD, PINK, AQUA, JADE, AMBER, OLD_LACE, WHITE, BLACK

strip = neopixel.NeoPixel(board.GP15, 30, brightness=1.0)

audio = AudioOut(board.GP16)

path = "sounds/"

filename = "organic.mp3" # change to valid file in your path
mp3_file = open(path + filename, "rb")
decoder = MP3Decoder(mp3_file)

def activate(filename, color, brightness):
    strip.fill(color)
    strip.brightness = brightness
    decoder.file = open(path + filename, "rb")
    audio.play(decoder)
    while audio.playing:
        pass
    strip.fill(0)

# Get adafruit io username and key from settings.toml
aio_username = os.getenv('AIO_USERNAME')
aio_key = os.getenv('AIO_KEY')

# Setup a feed: This may have a different name than your Dashboard
light_sound_feed = aio_username + "/feeds/light_sound_feed"

# Setup functions to respond to MQTT events
def connected(client, userdata, flags, rc):
    # Connected to broker at adafruit io
    print("Connected to Adafruit IO! Listening for topic changes in feeds I've subscribed to")
    # Subscribe to all changes on the feed.
    client.subscribe(light_sound_feed)

def disconnected(client, userdata, rc):
    # Disconnected from the broker at adafruit io
    print("Disconnected from Adafruit IO!")


def message(client, topic, message):
    # The bulk of your code to respond to MQTT will be here, NOT in while True:
    print(f"topic: {topic}, message: {message}")
    if topic == light_sound_feed: # robot directions
        if message == "organic":
            print("here")
            activate("organic.mp3", GREEN, 1.0)
        elif message == "glass":
            activate("glass.mp3", AQUA, 1.0)
        elif message == "paper":
            activate("paper.mp3", WHITE, 1.0)
        elif message == "metal":
            activate("metal.mp3", YELLOW, 1.0)
        elif message == "plastic":
            activate("plastic.mp3", BLUE, 1.0)
        elif message == "hazard":
            activate("hazard.mp3", RED, 1.0)
        elif message == "landfill":
            activate("landfill.mp3", (105,105,105), 0.1)
        elif message == "compost":
            activate("compost.mp3", (139,69,19), 1.0)

# Connect to WiFi
print(f"Connecting to WiFi")
wifi.radio.connect(os.getenv("WIFI_SSID"), os.getenv("WIFI_PASSWORD"))
print("Connected!")
strip.fill(0)

# Create a socket pool
pool = socketpool.SocketPool(wifi.radio)

# Set up a MiniMQTT Client - this is our current program that subscribes or "listens")
mqtt_client = MQTT.MQTT(
    broker=os.getenv("BROKER"),
    port=os.getenv("PORT"),
    username=aio_username,
    password=aio_key,
    socket_pool=pool,
    ssl_context=ssl.create_default_context(),
)

mqtt_client.connect()

# Setup the "callback" mqtt methods above
mqtt_client.on_connect = connected
mqtt_client.on_disconnect = disconnected
mqtt_client.on_message = message

# Connect to the MQTT broker (adafruit io for us)
print("Connecting to Adafruit IO...")
mqtt_client.connect()

mqtt_client.publish(light_sound_feed + "/get", "")
print("Robot Working!")

while True:
    mqtt_client.loop(2)