#!/usr/bin/env python3

import sys
import time
import os
import board
import keypad
import queue
import threading
from pygame import mixer

## Use the first argument as the delay
wait_seconds_raw = sys.argv[1]
wait_seconds = int(wait_seconds_raw)

# Import Adafruit IO REST client.
from Adafruit_IO import Client,  RequestError

## Set to your Adafruit IO key.
## Remember, your key is a secret,
## so make sure not to publish it when you publish this code!
ADAFRUIT_IO_KEY = 'YOUR_KEY_HERE'

## Set to your Adafruit IO username.
## (go to https://accounts.adafruit.com to find your username)
ADAFRUIT_IO_USERNAME = 'YOUR_USERNAME_HERE'

## Create an instance of the REST client.
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

## Sleep for a long time on bootup to give the wi-fi time to connect
time.sleep(wait_seconds) ## argument via command line

try:
    puppy_buttons_feed = aio.feeds('puppy-buttons')
except RequestError:
    print('could not find specified feed')

## Load the sounds:
mixer.init()
sound_applause = mixer.Sound('/home/pi/pianobar/wav_files/applause-1.wav')
sound_play       = mixer.Sound('/home/pi/pianobar/wav_files/play.wav')
sound_potty      = mixer.Sound('/home/pi/pianobar/wav_files/potty.wav')
sound_water      = mixer.Sound('/home/pi/pianobar/wav_files/water.wav')
sound_walk       = mixer.Sound('/home/pi/pianobar/wav_files/walk.wav')
sound_later      = mixer.Sound('/home/pi/pianobar/wav_files/later.wav')
sound_anabelle   = mixer.Sound('/home/pi/pianobar/wav_files/anabelle.wav')
sound_outside    = mixer.Sound('/home/pi/pianobar/wav_files/outside.wav')
sound_hmmm       = mixer.Sound('/home/pi/pianobar/wav_files/hmmm.wav')
sound_daddy      = mixer.Sound('/home/pi/pianobar/wav_files/daddy.wav')
sound_mommy      = mixer.Sound('/home/pi/pianobar/wav_files/mommy.wav')

sound_all_done   = mixer.Sound('/home/pi/pianobar/wav_files/all-done-happy-v2.wav')
sound_ball       = mixer.Sound('/home/pi/pianobar/wav_files/ball.wav')
sound_bed_time   = mixer.Sound('/home/pi/pianobar/wav_files/bed-time.wav')
sound_cuddles    = mixer.Sound('/home/pi/pianobar/wav_files/cuddles.wav')
sound_downstairs = mixer.Sound('/home/pi/pianobar/wav_files/downstairs.wav')
sound_hard       = mixer.Sound('/home/pi/pianobar/wav_files/hard-best-v4.wav')
sound_lazer      = mixer.Sound('/home/pi/pianobar/wav_files/lazer.wav')
sound_lila       = mixer.Sound('/home/pi/pianobar/wav_files/lila.wav')
sound_love_you   = mixer.Sound('/home/pi/pianobar/wav_files/love-you.wav')
sound_nap_time   = mixer.Sound('/home/pi/pianobar/wav_files/nap-time.wav')
sound_noise      = mixer.Sound('/home/pi/pianobar/wav_files/noise.wav')
sound_pets       = mixer.Sound('/home/pi/pianobar/wav_files/pets.wav')
sound_soft       = mixer.Sound('/home/pi/pianobar/wav_files/soft.wav')
sound_thea       = mixer.Sound('/home/pi/pianobar/wav_files/thea.wav')
sound_tug        = mixer.Sound('/home/pi/pianobar/wav_files/tug.wav')

sound_upstairs   = mixer.Sound('/home/pi/pianobar/wav_files/upstairs.wav')
sound_want       = mixer.Sound('/home/pi/pianobar/wav_files/want.wav')
sound_yard       = mixer.Sound('/home/pi/pianobar/wav_files/yard.wav')

km = keypad.KeyMatrix(
    row_pins=(board.D4, board.D7, board.D8, board.D11, board.D9, board.D10),
    column_pins=(board.D17, board.D18, board.D27, board.D22, board.D23, board.D24, board.D25),
    columns_to_anodes=True,
)
event_map = {
    1: sound_mommy,
    5: sound_daddy,
    21: sound_hmmm,
    22: sound_play,
    23: sound_outside,
    24: sound_potty,
    25: sound_water,
    27: sound_walk,
    26: sound_later,
}

def sound_player(play_queue, quit):
    while True:
        sound = play_queue.get()
        if quit.is_set():
            return
        sound.play()

def event_logger(log_queue, quit):
    while True:
        event_number = log_queue.get()
        if quit.is_set():
            return
        aio.send_data(puppy_buttons_feed.key, event_number)

log_queue = queue.Queue()
play_queue = queue.Queue()
quit_flag = threading.Event()

threads = [threading.Thread(target=sound_player, args=(play_queue, quit_flag)),
           threading.Thread(target=event_logger, args=(log_queue, quit_flag))]

## Code to actually ".Start()" the threads
for t in threads:
    t.start()

try:
    while True:
        event = km.events.get()
        # Maybe print the event here?...
        if not (event and event.pressed):
            continue
        if event.key_number == 0:
            break
        if event.key_number in event_map:
            play_queue.put(event_map[event.key_number])
            log_queue.put(event.key_number)

finally:
    quit_flag.set()
    # Put "None" into the queues to wake up the threads blocking in queue.get()
    log_queue.put(None)
    play_queue.put(None)
    for t in threads:
        t.join()

os.system('sudo shutdown now -h')
exit(0)