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

# SMART SPEAKER THEATRE
# This script reads the triggers for activated user intents sent by Snips over MQTT
# Using this triggers, it will start particular actions and scripts


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


# === SETUP OF MQTT PART 1 ===

# Location of the MQTT server
HOST = 'localhost'
PORT = 1883

# Subscribe to relevant MQTT topics
def on_connect(client, userdata, flags, rc):
    print("Connected to {0} with result code {1}".format(HOST, rc))
    client.subscribe('hermes/intent/jocavdh:play_intro_act') # to check for intent to play the act
    client.subscribe('hermes/intent/jocavdh:question_continue_act') # to check for the intent to continue to the next act
    client.subscribe('hermes/hotword/default/detected')




# === FUNCTIONS THAT ARE TRIGGERED WHEN AN INTENT IS DETECTED ===

def on_wakeword(client, userdata, msg):
    pixel_ring.think()

# Function which is triggered when the intent play_intro_act is activated
def on_play_act(client, userdata, msg):
    

    # # disable this intent to avoid playing another act triggered by the Google Home
    # client.publish("hermes/dialogueManager/configure", json.dumps({
	# 	'siteId': 'default',
	# 	'intents': {
	# 		'jocavdh:play': False
	# 	}
	# }))

    call(["python3", "act.py", "play_scripts/demo.txt"])

# Function which is triggered when the intent introduction is activated
def on_play_introduction(client,data,msg):

    for character, line, direction in read_script('plays/introduction.txt'):
        input_text = line
        voice = characters.get(character)[0]
        speaker = characters.get(character)[1]
        action = directions.get(direction[0])
        tts(voice, input_text, speaker)        
        sleep(1) # add a pause between each line


    print('The act is over.')



# === SETUP OF MQTT PART 2 ===

# Initialise MQTT client
client = mqtt.Client()
client.connect(HOST, PORT, 60)
client.on_connect = on_connect

# Connect each MQTT topic to which you subscribed to a handler function
client.message_callback_add('hermes/intent/jocavdh:play_intro_act', on_play_act)
client.message_callback_add('hermes/hotword/default/detected', on_wakeword)

# Keep checking for new MQTT messages
client.loop_forever()