#!/usr/bin/env python3
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#	 http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Run a recognizer using the Google Assistant Library.

The Google Assistant Library has direct access to the audio API, so this Python
code doesn't need to record audio. Hot word detection "OK, Google" is supported.

It is available for Raspberry Pi 2/3 only; Pi Zero is not supported.
"""

import logging
import platform
import subprocess
import sys

from google.assistant.library.event import EventType

from aiy.assistant import auth_helpers
from aiy.assistant.library import Assistant
from aiy.board import Board, Led
from aiy.voice import tts

import paho.mqtt.subscribe as subscribe
from time import sleep as time_sleep
from utility import fileexists
from datetime import datetime
from sys import exit as sys_exit
from config import class_config

def power_off_pi():
	tts.say('Good bye!')
	subprocess.call('sudo shutdown now', shell=True)

def reboot_pi():
	tts.say('See you in a bit!')
	subprocess.call('sudo reboot', shell=True)

def say_ip():
	ip_address = subprocess.check_output("hostname -I | cut -d' ' -f1", shell=True)
	tts.say('My IP address is %s' % ip_address.decode('utf-8'))

def say_sauna(config):
	#global subscribe
	latest_msg = subscribe.simple(config.topic, msg_count = 1, hostname = config.broker_address, \
		retained = True,port = 1883)
	msg = latest_msg.payload.decode()
	tts.say("sauna temp is " + msg)

def process_event(assistant, led, event):
	global config
	logging.info(event)
	if event.type == EventType.ON_START_FINISHED:
		led.state = Led.BEACON_DARK  # Ready.
		print('Say "OK, Google" then speak, or press Ctrl+C to quit...')
	elif event.type == EventType.ON_CONVERSATION_TURN_STARTED:
		led.state = Led.ON  # Listening.
	elif event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED and event.args:
		print('You said:', event.args['text'])
		text = event.args['text'].lower()
		if text == 'power off':
			assistant.stop_conversation()
			power_off_pi()
		elif text == 'reboot':
			assistant.stop_conversation()
			reboot_pi()
		elif text == 'ip address':
			assistant.stop_conversation()
			say_ip()
		elif text == 'house stuff':
			assistant.stop_conversation()
			say_sauna(config)
	elif event.type == EventType.ON_END_OF_UTTERANCE:
		led.state = Led.PULSE_QUICK  # Thinking.
	elif (event.type == EventType.ON_CONVERSATION_TURN_FINISHED
		or event.type == EventType.ON_CONVERSATION_TURN_TIMEOUT
		or event.type == EventType.ON_NO_RESPONSE):
		led.state = Led.BEACON_DARK  # Ready.
	elif event.type == EventType.ON_ASSISTANT_ERROR and event.args and event.args['is_fatal']:
		sys.exit(1)

def main():
	global config
	config = class_config()
	if fileexists(config.config_filename):		
		print( "will try to read Config File : " ,config.config_filename)
		config.read_file() # overwrites from file
	else : # no file so file needs to be writen
		config.write_file()
		print("New Config File Made with default values, you probably need to edit it")

	logging.basicConfig(level=logging.INFO)

	credentials = auth_helpers.get_assistant_credentials()
	with Board() as board, Assistant(credentials) as assistant:
		for event in assistant.start():
			process_event(assistant, board.led, event)

if __name__ == '__main__':
	main()
