# Libraries
import re
from config import characters, directions
from logic import tts, read_script, select_script, led_on, led_off
from subprocess import call
import paho.mqtt.client as mqtt
import json
from time import sleep
from pixel_ring import pixel_ring
import serial
from tuning import Tuning
import usb.core
import usb.util
import sys

# Set up serial connection with the microcontroller that controls the speaker LED's
ser = serial.Serial('/dev/ttyACM0', 9600) 
file = sys.argv[1] # get the chosen act passed by smart_speaker_theatre.py

# Function to do the play
i = True

if i:
    for character, line, direction in read_script(file):
        input_text = line
        voice = characters.get(character)[0]
        speaker = characters.get(character)[1]
        action = directions.get(direction[0])
        print(direction)
        print(action)
        led_on(ser, speaker)
        tts(voice, input_text, speaker)
        led_off(ser, speaker)

        if action == 'listen_google_home':
            dev = usb.core.find(idVendor=0x2886, idProduct=0x0018)
            print('Wait for Google Home')
            Mic_tuning = Tuning(dev)
            VAD = Mic_tuning.is_voice()
            counter= 0
            voice_detected = 1

            sleep(4)

            while voice_detected == 1:
                    
                    print(VAD)

                    VAD = Mic_tuning.is_voice()

                    if VAD == 1:
                        counter = 0
                        print('still speaking')

                    if VAD == 0:
                        counter+=1
                        print('silence detected')

                    if counter == 30:
                        print('no voice detected')
                        voice_detected = 0
                    
                    print(counter)
                        
                            
                
            print('Google Home is done')

        if action == 'congress.wav':
            print('play audioclip')
            playing = True

            while playing:
                call(["aplay", "-D", speaker, "sounds/congress.wav"])
                playing = False

        if action == 'genie.wav':
            print('play audioclip')
            playing = True

            while playing:
                call(["aplay", "-D", speaker, "sounds/genie.wav"])
                playing = False
           

        sleep(1) # Add a short pause between the lines


    print('The act is done.')

# Function to control the LED's of the speakers