from gtts import gTTS
import pywapi
import string
import mraa
import subprocess
import time
import datetime
import calendar
import threading

import pprint
pp = pprint.PrettyPrinter(indent=4)

#initialize Buttons
bu1 = mraa.Gpio(2)
bu1.dir(mraa.DIR_IN)
bu2 = mraa.Gpio(3)
bu2.dir(mraa.DIR_IN)

button1Pressed = False
button2Pressed = False
alarmActive = False
lightActive = False
alarmDone = True
alarmTime = calendar.timegm(time.localtime()) + 3600	#initialize
snoozeTime = 0

#32, 33, 34, 35
SEGMENT1 = 34
SEGMENT2 = 35
SEGMENT3 = 33
SEGMENT4 = 32
x = mraa.I2c(0)

oldVal1 = 0
oldVal2 = 0
oldVal3 = 0
oldVal4 = 0


#Main-Loop is executed all 100 ms and handles input/output
def mainLoop():
	#Check if alarm is ready
	global SEGMENT1, SEGMENT2, SEGMENT3, SEGMENT4
	global alarmTime, lightActive, alarmActive, snoozeTime
	global x
	global button1Pressed, button2Pressed
	
	ledTime = alarmTime - 600
	#Is it time for the light-loop?
	#5 min before alarm
	if ((calendar.timegm(time.localtime()) > ledTime) and (lightActive == False)):
		lightActive = True
		threading.Timer(60, lightUp).start()
		threading.Timer(120, lightUp).start()
		threading.Timer(180, lightUp).start()
		threading.Timer(240, lightUp).start()		
		lightOn()
	
	#First check Alarm
	if (calendar.timegm(time.localtime()) > alarmTime):
		playAlarm()
	
	#Sometimes there is an I2c-Bus Error
	try:
		x.address(SEGMENT1)
		res1 = x.readByte()
		x.address(SEGMENT2)
		res2 = x.readByte()
		x.address(SEGMENT3)
		res3 = x.readByte()
		x.address(SEGMENT4)
		res4 = x.readByte()
		
		getClockTime(res1, res2, res3, res4)
	except:
		print "Error I2C Bus"

	#DEBUG
	#print alarmTime
	#print calendar.timegm(time.localtime())
	
	if (bu1.read() == True):
		#One button was pressed
		if button1Pressed == False:
					print "button 1 pressed"
					threading.Timer(1, unsetButton1).start()
					button1Pressed = True;
					if (alarmActive == True):
						print "Disable Alarm"
						alarmActive = False
						subprocess.Popen(["/usr/bin/killall", "-2", "mpg123"])
						lightOut()
						snoozeTime = 0		#disable snooze
					else:
						print "Say Time"
						sayTime()
					
	if (bu2.read() == True):
		#One button was pressed
		if button2Pressed == False:
					print "button 2!"
					threading.Timer(1, unsetButton2).start()
					button2Pressed = True;					
					if (alarmActive == True):
						#alarm has to be stopped and snoozeTime increased
						print "Increase Snooze"
						snoozeTime = snoozeTime + 300
						alarmActive = False
						subprocess.Popen(["/usr/bin/killall", "-2", "mpg123"])
						lightOut()
					else:
						print "Say wakup-time"
						sayAlarmTime()
	threading.Timer(0.1, mainLoop).start()

def getNumberFromSegment(state):
	retVal = -1;
	if (state == 159):
		retVal = 1
	elif (state == 162):
		retVal = 2
	elif (state == 134):
		retVal = 3
	elif (state == 149):
		retVal = 4
	elif (state == 196):
		retVal = 5
	elif (state == 192):
		retVal = 6
	elif (state == 158):
		retVal = 7
	elif (state == 128):
		retVal = 8
	elif (state == 132):
		retVal = 9
	elif (state == 136):
		retVal = 0
	return retVal

def getClockTime(s1, s2, s3, s4):
	global alarmTime, snoozeTime
	n1 = getNumberFromSegment(s1)
	n2 = getNumberFromSegment(s2)
	n3 = getNumberFromSegment(s3)
	n4 = getNumberFromSegment(s4)

	#if not a number, return funtcion
	if ((n1 == -1) or (n2 == -1) or (n3 == -1) or (n4 == -1)):
		#print "DEBUG: Segment not a number"
		return -1
	#some segments have disallowed numbers
	if (n1 > 2) or (n3 > 5):
		#print "DEBUG: Time out of range"
		return -1

	retString = str(n1) + str(n2) + ":" + str(n3) + str(n4)

	startTime=datetime.datetime(int(time.strftime("%Y")), int(time.strftime("%m")), int(time.strftime("%d")), 0, 0)	
	startTimeEpoch = calendar.timegm(startTime.timetuple())

	#Berechne naechsten weckzeitpunkt
	nextAlarmTime = startTimeEpoch + n1 * 10 * 3600 + n2 * 3600 + n3 * 10 * 60 + n4 * 60 + snoozeTime

	#If the alarn time is smaller than the current time add 24 hours
	if (nextAlarmTime < calendar.timegm(time.localtime())):
		nextAlarmTime = nextAlarmTime + 24 * 3600
	#print "DEBUG: New alarm time " + time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(nextAlarmTime))

	alarmTime = nextAlarmTime
	return nextAlarmTime

def unsetButton1():
	global button1Pressed
	button1Pressed = False

def unsetButton2():
	global button2Pressed
	button2Pressed = False

def playAlarm():
	print "RingRing"
	playMorning()

	
def lightOn():
	global x
	try:
		#x.address(8)
        	x.write(bytearray(b'FFE01F'))
        	print("sent ON signal: 0xFFE01F")
        	x.write(bytearray(b'FFD02F'))
        	print("sent WHITE signal: 0xFFD02F")
		
		x.address(8)
        	x.write(bytearray(b'FFE01F'))
		print("sent ON signal: 0xFFE01F")
        	x.write(bytearray(b'FFD02F'))
        	print("sent WHITE signal: 0xFFD02F")
		
		x.address(8)
        	x.write(bytearray(b'FFE01F'))
       		print("sent ON signal: 0xFFE01F")
        	x.write(bytearray(b'FFD02F'))
        	print("sent WHITE signal: 0xFFD02F")
		
	except:
		print "LightOn-Exception"
	print "LightOn"

def lightUp():
	global x
	try:
		x.address(8)
        	x.write(bytearray(b'FFA05F'))
        	print("sent UP signal: 0xFFA05F")
	except:
		print "UPException"
	print "LightUp"

def lightDown():
	global x
	try:
		x.address(8)
        	x.write(bytearray(b'FF609F'))
        	print("sent DOWN signal: FF609F")
        	x.write(bytearray(b'FF609F'))
        	print("sent DOWN signal: FF609F")
        	x.write(bytearray(b'FF609F'))
        	print("sent DOWN signal: FF609F")			
	except:
		print "DOWNException"
	print "LightUp"
	
def lightOut():
	global x, lightActive
	lightActive = False
	try:
		x.address(8)
        	x.write(bytearray(b'FFA05F'))
        	print("sent OUT signal: 0xFFA05F")
	except:
		print "OUTException"
	print "LightOUT"

	
def sayTime():
	aTime = "It is " + time.strftime("%H:%M", time.localtime()) + " and " + time.strftime("%S", time.localtime()) + " seconds"	
	print aTime
	try:
		tts = gTTS(text=aTime, lang='en')
		tts.save("myTime.mp3")
		subprocess.Popen(["/usr/bin/mpg123","/home/root/myTime.mp3"])
	except:
		print "tts error"
	
def sayAlarmTime():
	global alarmTime
	aTime = "The alarm is set to " + time.strftime("%H:%M", time.gmtime(alarmTime))	
	try:
		print aTime
		tts = gTTS(text=aTime, lang='en')
		tts.save("myTime.mp3")
		subprocess.Popen(["/usr/bin/mpg123","/home/root/myTime.mp3"])
	except:
		print "tts error"
	
def playMorning():
	#How to find the right place
	#Bad Aibiling GMXX2598
	#Bruckmuehl GMXX6148
	#a = pywapi.get_loc_id_from_weather_com("Bruckm")
	#print(a)
	global alarmActive
	alarmActive = True

	weather_com_result = pywapi.get_weather_from_weather_com('GMXX6148')
	weatherText = "Good Morning! "
	weatherText += ("It is " + weather_com_result['current_conditions']['text'].lower() + " and " + weather_com_result['current_conditions']['temperature'] + " degree Celsius ouside.\n")
	
	cloudstat = string.replace(str(weather_com_result['forecasts'][0]['day']['brief_text'].lower()), "p cloudy", "partially cloudy")
	weatherText += ("The forecast for today: " + cloudstat + " with a " + weather_com_result['forecasts'][0]['day']['chance_precip'] + " percent chance of rain.\n")
	
	mintemp = str(weather_com_result['forecasts'][0]['low'])
	maxtemp = str(weather_com_result['forecasts'][0]['high'])
	weatherText += ("Maximum and minimum temperatures: " + mintemp + " and " + maxtemp + " degree celsius.\n")
	
	sunrise = str(weather_com_result['forecasts'][0]['sunrise'])
	weatherText += ("The sun rises at: " + sunrise + ".\n")
	
	print (weatherText)
	#pp.pprint( weather_com_result['forecasts'][0]['day']['brief_text'].lower() )
	
	try:
		tts = gTTS(text=weatherText, lang='en')
		tts.save("myTest.mp3")
		subprocess.Popen(["/usr/bin/mpg123","/home/root/myTest.mp3"])
	except:
		print "error creating tts"
	time.sleep(20)
	subprocess.Popen(["/usr/bin/mpg123","/home/root/WAVEs/wakeup.mp3"])

mainLoop()
