#!/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, select_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') # to check for intent to play the act
    client.subscribe('hermes/intent/jocavdh:play_question') # to check for the intent to continue to the next act
    client.subscribe('hermes/intent/jocavdh:play_verdict') # to check for the intent to continue to the next act
    client.subscribe('hermes/hotword/default/detected')
    client.subscribe("hermes/asr/textCaptured")
    client.subscribe("hermes/dialogueManager/sessionQueued")




# === 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 introduction is activated
def on_play_intro(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
	# 	}
	# }))
    import pdb; pdb.set_trace()
    path = 'scripts_play/intro/'
    call(["python3", "act.py", 'scripts_play/intro/introduction_01.txt'])
    print('The act is over.')

    #on_play_question(client, userdata, msg)

# Function which is triggered when the intent for another question is activated
def on_play_question(client, userdata, msg):

    path = 'scripts_play/questions/'
    call(["python3", "act.py", select_script(path)])
    print('The act is over.')

# Function which is triggered when the intent for another question is activated
def on_play_verdict(client, userdata, msg):

    path = 'scripts_play/verdict/'
    call(["python3", "act.py", select_script(path)])
    print('The play 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/hotword/default/detected', on_wakeword)
client.message_callback_add('hermes/intent/jocavdh:play_intro', on_play_intro)
client.message_callback_add('hermes/intent/jocavdh:play_question', on_play_question)
client.message_callback_add('hermes/intent/jocavdh:play_verdict', on_play_verdict)


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