#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# PLAY_ACT.py
# This script runs the play


# Libraries
from config import characters, directions
from logic import tts, read_script,listen
from subprocess import call
import paho.mqtt.client as mqtt
import json
import sys
from time import sleep

# Switch of LED's of speakers at the start of the play
#pixel_ring.off()

import serial
from pixel_ring import pixel_ring
ser = serial.Serial('/dev/ttyACM0', 1000000) # Establish the connection on a specific port

def led_on(speaker):    

    if speaker == 'mono3':
        ser.write(b'3')
    
    if speaker == 'mono1':
        ser.write(b'1')
    
    if speaker == 'mono2':
        pixel_ring.speak()

def led_off(speaker):

    if speaker == 'mono3':
        ser.write(b'4')
    
    if speaker == 'mono1':
        ser.write(b'2')
    
    if speaker == 'mono2':
        pixel_ring.off()



# Read the script and run the play


file = sys.argv[1] # get the chosen act passed by smart_speaker_theatre.py

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])

    led_on(speaker)

    tts(voice, input_text, speaker)

    if action == 'listen_google_home':
        listen()

    if action == 'music':
        print('play audioclip')
        playing = True

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

            
    led_off(speaker)
    sleep(0.2) # Add a short pause between the lines


print('The act is done.')