#!/usr/bin/python
# Written by Robin Burchell  
# No licence specified or required, but please give credit where it's due, and please let me know if this helped you.
# Feel free to contact with corrections or suggestions.
#
# We're using PySide, Nokia's official LGPL bindings.
# You can however easily use PyQt (Riverside Computing's GPL bindings) by commenting these and fixing the appropriate imports.
import sys
import os
import subprocess
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtMaemo5 import QMaemo5ValueButton, QMaemo5ListPickSelector, QMaemo5TimePickSelector
 
# In Qt, everything is a class.
# We can subclass stuff to do whatever we want - it seems a bit strange at first,
# but it keeps all related functionality in one place, which helps to keep you organised.
#
# We're subclassing 'QWidget' here. QWidget is the base class for all graphical elements in Qt.
# You can do all sorts of cool things like drawing your widget yourself, but we won't get into that.
#
# See also:
#   http://doc.trolltech.com/4.6/qwidget.html

#########################
# Some global variables #
#########################
CooktimerVersion = "0.0.1-8"
Vibration = True
Sound = True
Wakeup = True
Home = os.path.expanduser("~")
CommentChar = '#'
OptionChar =  ' '
Cooktimer_CfgDir = Home + '/.config/cooktimer/'
Cooktimer_CfgFile = Cooktimer_CfgDir + 'cooktimer.cfg'
Cooktimer_ItemFile = Cooktimer_CfgDir + 'cooktimer.items'
Language = os.getenv('LANG')
Player = "play-sound"

def parse_config(self, filename):
	options = {}
	f = open(filename)
	for line in f:
		# First, remove comments:
		if CommentChar in line:
			# split on comment char, keep only the part before
			line, comment = line.split(CommentChar, 1)
		# Second, find lines with an option=value:
		if OptionChar in line:
			# split on option char:
			option, value = line.split(OptionChar, 1)
			# strip spaces:
			option = option.strip()
			value = value.strip()
			# store in dictionary:
			options[option] = value
	f.close()
 	return options


def Alarm(self):
	if Wakeup:
		# Switch on backlight to be sure message is displayed
		strUnlock = "dbus-send --print-reply --system --dest=com.nokia.mce /com/nokia/mce/request com.nokia.mce.request.req_tklock_mode_change string:unlocked"
		QProcess.startDetached(strUnlock)
	if Vibration:
		os.system('dbus-send --system --print-reply --dest=com.nokia.mce /com/nokia/mce/request com.nokia.mce.request.req_start_manual_vibration int32:250 int32:3000 >/dev/null')
	if Sound:
		SoundString = Player + " /opt/cooktimer/alarm-cooktimer.wav"
		QProcess.startDetached(SoundString)

def format_seconds_to_hhmmss(seconds):
	hours = seconds // (60*60)
	seconds %= (60*60)
	minutes = seconds // 60
	seconds %= 60
	return "%02i:%02i:%02i" % (hours, minutes, seconds)


class MyMainWindow(QMainWindow):
    def __init__(self, parent=None):# first things first, we need to initialise the Qt parent, otherwise it won't work properly.
        #
	super(MyMainWindow, self).__init__(parent)
        self.setAttribute(Qt.WA_Maemo5StackedWindow)
	self.setAttribute(Qt.WA_Maemo5AutoOrientation, True)
	# Create config dir if needed
	if not os.path.exists(Cooktimer_CfgDir):
		os.mkdir(Cooktimer_CfgDir)
	# Create config files if needed
	if not os.path.isfile(Cooktimer_CfgFile):
		try:
			newConfigFile = open(Cooktimer_CfgFile,"w")
		except:
			QMessageBox.critical(self, "Warning",  "Cannot write " + Cooktimer_CfgFile)
		else:
			newConfigFile.write("keepbacklighton true\n")
			newConfigFile.write("vibration true\n")
			newConfigFile.write("wakeup true\n")
			newConfigFile.write("sound true\n")
			newConfigFile.close()
	else:
		keepbacklightset = False
		vibrationset = False
		wakeupset = False
		soundset = False
		ConfigFile = open(Cooktimer_CfgFile,"r")
		lines = ConfigFile.readlines()
		for line in lines:
			if 'keepbacklighton' in line:
				keepbacklightset = True
			if 'vibration' in line:
				vibrationset = True
			if 'wakeup' in line:
				wakeupset = True
			if 'sound' in line:
				soundset = True
		ConfigFile.close()
		if not keepbacklightset or not vibrationset or not wakeupset or not soundset:
			ConfigFile = open(Cooktimer_CfgFile,"a")
			if not keepbacklightset:
				ConfigFile.write("keepbacklighton true\n")
			if not vibrationset:
				ConfigFile.write("vibration true\n")
			if not wakeupset:
				ConfigFile.write("wakeup true\n")
			if not soundset:
				ConfigFile.write("sound true\n")
			ConfigFile.close()
	if not os.path.isfile(Cooktimer_ItemFile):
		try:
			newConfigFile = open(Cooktimer_ItemFile,"w")
		except:
			QMessageBox.critical(self, "Warning",  "Cannot write " + Cooktimer_ItemFile)
		else:
			newConfigFile.close()
	self.form_widget = FormWidget(self)
	self.setCentralWidget(self.form_widget)
	###############
	# read config #
	###############
	global OptionChar
	OptionChar = " "
	self.cooktimer_opts = parse_config(self,Cooktimer_CfgFile)
	##############
	# Set player #
	##############
	global Player
	ProfileCmd = "dbus-send --type=method_call --print-reply --dest=com.nokia.profiled /com/nokia/profiled com.nokia.profiled.get_profile"
	fin,fout = os.popen4(ProfileCmd)
	CurrProfile = fout.read().split()[-1].strip('"')
	if CurrProfile == "silent":
		if os.path.isfile("/usr/bin/mplayer"):
			Player = "mplayer"
	###############
	# Create menu #
	###############
	saveAction = QAction( '&Save config', self)
	editAction = QAction( '&Edit items', self)
	aboutAction = QAction( '&About', self)
	self.backlightAction = QAction( '&Keep backlight on', self)
	self.backlightAction.setCheckable(True)
	if self.cooktimer_opts["keepbacklighton"] == "true":
		self.backlightAction.setChecked(True)
	self.wakeupAction = QAction( '&Wakeup screen on alarm', self)
	self.wakeupAction.setCheckable(True)
	if self.cooktimer_opts["wakeup"] == "true":
		self.wakeupAction.setChecked(True)
	self.vibrateAction = QAction( '&Vibrate on alarm', self)
	self.vibrateAction.setCheckable(True)
	if self.cooktimer_opts["vibration"] == "true":
		self.vibrateAction.setChecked(True)
	self.soundAction = QAction( '&Sound on alarm', self)
	self.soundAction.setCheckable(True)
	if self.cooktimer_opts["sound"] == "true":
		self.soundAction.setChecked(True)

	self.setWindowTitle(self.tr("Cooktimer"))

	menubar = self.menuBar()
	mainMenu = menubar.addMenu('&MainMenu')
	mainMenu.addAction(self.backlightAction)
	mainMenu.addAction(self.wakeupAction)
	mainMenu.addAction(self.vibrateAction)
	mainMenu.addAction(self.soundAction)
	mainMenu.addAction(saveAction)
	mainMenu.addAction(editAction)
	mainMenu.addAction(aboutAction)


	self.backlightAction.triggered.connect(self.backlightPushed)
	self.wakeupAction.triggered.connect(self.wakeupPushed)
	self.vibrateAction.triggered.connect(self.vibratePushed)
	self.soundAction.triggered.connect(self.soundPushed)
	saveAction.triggered.connect(self.savePushed)
	editAction.triggered.connect(self.editPushed)
	aboutAction.triggered.connect(self.aboutPushed)

	#############################
	# Prevent backlight dimming #
	#############################
	self.dimtimer = QTimer()
	self.dimtimer.timeout.connect(self.KeepBackLightOn)
	self.screendim_timeout = int(os.popen('gconftool-2 --get /system/osso/dsm/display/display_dim_timeout').read())*1000
	if self.cooktimer_opts["keepbacklighton"] == "true":
		self.dimtimer.start(self.screendim_timeout)

    def KeepBackLightOn(self):
	strUnlock = "dbus-send --system --type=method_call --dest=com.nokia.mce /com/nokia/mce/request com.nokia.mce.request.req_display_blanking_pause"
	QProcess.startDetached(strUnlock)

    def wakeupPushed(self):
	global Wakeup
	if self.wakeupAction.isChecked():
		Wakeup = True
	else:
		Wakeup = False

    def backlightPushed(self):
	if self.dimtimer.isActive():
		self.dimtimer.stop()
	else:
		self.dimtimer.start(self.screendim_timeout)

    def vibratePushed(self):
	global Vibration
	if self.vibrateAction.isChecked():
		Vibration = True
	else:
		Vibration = False

    def soundPushed(self):
	global Sound
	if self.soundAction.isChecked():
		Sound = True
	else:
		Sound = False
	

    def savePushed(self):
	if self.vibrateAction.isChecked():
		self.cooktimer_opts["vibration"] = "true"
	else: self.cooktimer_opts["vibration"] = "false"
	if self.backlightAction.isChecked():
		self.cooktimer_opts["keepbacklighton"] = "true"
	else: self.cooktimer_opts["keepbacklighton"] = "false"
	if self.wakeupAction.isChecked():
		self.cooktimer_opts["wakeup"] = "true"
	else: self.cooktimer_opts["wakeup"] = "false"
	try:
		newConfigFile = open(Cooktimer_CfgFile,"w")
		for option in self.cooktimer_opts:
			newConfigFile.write(option + " " + self.cooktimer_opts[option] + "\n")
		newConfigFile.close()
		os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
			/org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
			string:"Configuration is succesfully saved"')
	except:
		os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
			/org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
			string:"Could NOT save Configuration!"')
	
    def editPushed(self):
	widget = itemWindow(self)
	widget.show()

    def aboutPushed(self):
	d = QDialog(self)
	vbox = QVBoxLayout()
	verticalLayout = QVBoxLayout() 
	verticalLayout.addWidget(QLabel("<center><img src=/opt/usr/share/icons/hicolor/64x64/apps/cooktimer.png /></center>"),0)
	verticalLayout.addWidget(QLabel("<center>Created by Arno Dekker (ade)</center>"),1)
	verticalLayout.addWidget(QLabel("<center>Version "+CooktimerVersion+"</center>"),2)
	vbox.addLayout (verticalLayout)
	d.setLayout(vbox)
	d.show()

class itemWindow(QDialog):
    def __init__(self, parent=None):
	super(itemWindow, self).__init__(parent)
	self.setWindowTitle("Item config")
	global OptionChar
	# Layout
	area = QScrollArea(self)
	lay = QVBoxLayout(self)
	lay.addWidget(area)
	wg = QWidget()
	area.setWidget(wg)
	screenGeometry = QApplication.desktop().screenGeometry()
	if screenGeometry.width() > screenGeometry.height():
		# landscape mode
		wg.resize(750,1050)
	else:
		# portrait mode
		wg.resize(750,1050)
	grid = QGridLayout(wg)
	wg.show()
	area.show()
	grid.setColumnMinimumWidth(0,200)
	grid.setHorizontalSpacing(0)
	grid.setVerticalSpacing(0)
	self.saveItemButton = QPushButton("SAVE",self)
	self.saveItemButton.setStyleSheet(
	"QPushButton { color: red; font:bold; }"
		)
	grid.addWidget(QLabel("<font color=red><center>Save below! [empty item and save to delete] </center></font>"),0,0,1,4)
        grid.addWidget(self.saveItemButton,17,0,1,4)
        grid.addWidget(QLabel("<center>Item</center>"), 1, 0)
        grid.addWidget(QLabel("<center>Hours</center>"), 1, 1)
        grid.addWidget(QLabel("<center>Minutes</center>"), 1, 2)
        grid.addWidget(QLabel("<center>Seconds</center>"), 1, 3)
	OptionChar =  '|'
	cooktimer_items = parse_config(self,Cooktimer_ItemFile)
	minTimeValue=0
	maxTimeHhValue=23
	maxTimeMiValue=59
	maxTimeSsValue=59
	maxLen=25
	teller=2
	var_num=1
	DishList = ""
	# make a new list for sorting case-insensitive
	for item in cooktimer_items:
		DishList = DishList + item + '|' + cooktimer_items[item] + "\n"
	contentsList = DishList.split('\n')
	contentsList = contentsList[:-1]
	contentsList.sort(lambda a, b: cmp(a.upper(), b.upper()))
	for dish in contentsList:
		item, value  = dish.split('|',1)
#	for item in cooktimer_items:
		hh_mi_ss = cooktimer_items[item].split(':',2)
		hh = hh_mi_ss[0]
		mi = hh_mi_ss[1]
		ss = hh_mi_ss[2]
		globals()['ItemName%s' % var_num] = QLineEdit(item)
		globals()['ItemName%s' % var_num].setMaxLength(maxLen)
		grid.addWidget(globals()['ItemName%s' % var_num],teller,0)
		globals()['HHSpinBox%s' % var_num] = QDoubleSpinBox()
		globals()['HHSpinBox%s' % var_num].setRange(minTimeValue, maxTimeHhValue)
		globals()['HHSpinBox%s' % var_num].setValue(float(hh))
		globals()['HHSpinBox%s' % var_num].setDecimals(0)
		globals()['HHSpinBox%s' % var_num].setAlignment(Qt.AlignCenter)
		grid.addWidget(globals()['HHSpinBox%s' % var_num], teller, 1)
		globals()['MISpinBox%s' % var_num] = QDoubleSpinBox()
		globals()['MISpinBox%s' % var_num].setRange(minTimeValue, maxTimeMiValue)
		globals()['MISpinBox%s' % var_num].setValue(float(mi))
		globals()['MISpinBox%s' % var_num].setDecimals(0)
		globals()['MISpinBox%s' % var_num].setAlignment(Qt.AlignCenter)
		grid.addWidget(globals()['MISpinBox%s' % var_num], teller, 2)
		globals()['SSSpinBox%s' % var_num] = QDoubleSpinBox()
		globals()['SSSpinBox%s' % var_num].setRange(minTimeValue, maxTimeMiValue)
		globals()['SSSpinBox%s' % var_num].setValue(float(ss))
		globals()['SSSpinBox%s' % var_num].setDecimals(0)
		globals()['SSSpinBox%s' % var_num].setAlignment(Qt.AlignCenter)
		grid.addWidget(globals()['SSSpinBox%s' % var_num], teller, 3)
		teller +=1
		var_num +=1

	for count in range(teller,17):
		globals()['ItemName%s' % var_num] = QLineEdit()
		globals()['ItemName%s' % var_num].setMaxLength(maxLen)
		grid.addWidget(globals()['ItemName%s' % var_num],teller,0)
		globals()['HHSpinBox%s' % var_num] = QDoubleSpinBox()
		globals()['HHSpinBox%s' % var_num].setRange(minTimeValue, maxTimeHhValue)
		globals()['HHSpinBox%s' % var_num].setDecimals(0)
		globals()['HHSpinBox%s' % var_num].setAlignment(Qt.AlignCenter)
		grid.addWidget(globals()['HHSpinBox%s' % var_num], teller, 1)
		globals()['MISpinBox%s' % var_num] = QDoubleSpinBox()
		globals()['MISpinBox%s' % var_num].setRange(minTimeValue, maxTimeMiValue)
		globals()['MISpinBox%s' % var_num].setDecimals(0)
		globals()['MISpinBox%s' % var_num].setAlignment(Qt.AlignCenter)
		grid.addWidget(globals()['MISpinBox%s' % var_num], teller, 2)
		globals()['SSSpinBox%s' % var_num] = QDoubleSpinBox()
		globals()['SSSpinBox%s' % var_num].setRange(minTimeValue, maxTimeMiValue)
		globals()['SSSpinBox%s' % var_num].setDecimals(0)
		globals()['SSSpinBox%s' % var_num].setAlignment(Qt.AlignCenter)
		grid.addWidget(globals()['SSSpinBox%s' % var_num], teller, 3)
		teller +=1
		var_num +=1

	self.connect(self.saveItemButton, SIGNAL("clicked()"),self.Saveitems)

    def Saveitems(self):
	try:
		newItemFile = open(Cooktimer_ItemFile,"w")
	except:
		QMessageBox.critical(self, "Warning",  "Cannot write " + Cooktimer_ItemFile)	
	else:
		for count in range(1,16):
			if globals()['ItemName%s' % count ].text() != "": 
				newItemFile.write(globals()['ItemName%s' % count ].text() + "|" + \
				'%02d' % int(globals()['HHSpinBox%s' % count ].value()) + ":" + \
				'%02d' % int(globals()['MISpinBox%s' % count ].value()) + ":" + \
				'%02d' % int(globals()['SSSpinBox%s' % count ].value()) + "\n")
		newItemFile.close()
		os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
			/org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
			string:"Configuration is succesfully saved\nRestart cooktimer to take effect"')


 
class FormWidget(QWidget):
    def __init__(self, parent):
        super(FormWidget, self).__init__(parent)

        # Now we start getting into building our interface. The first thing we need to learn about are layouts.
        # Layouts tell Qt where to put widgets, and how they fit with other widgets.
        # Unlike Gtk+, Qt layouts are *not* widgets - important difference to keep in mind.
        #
        # There are many types of layouts (from the complex, like QGridLayout) 
        # to the simple, like what we're using here.
        # See also:
        #   http://doc.trolltech.com/4.6/qlayout.html
        #   http://doc.trolltech.com/4.6/qvboxlayout.html
	global OptionChar
        grid = QGridLayout()
	
	# Timer1
	self.Timer1 = QTimer()
	self.Timer1.timeout.connect(self.updateTimer1)
	# Timer2
	self.Timer2 = QTimer()
	self.Timer2.timeout.connect(self.updateTimer2)
	# Timer3
	self.Timer3 = QTimer()
	self.Timer3.timeout.connect(self.updateTimer3)
 
	self.gerechten = [['','00:00:00']]
	OptionChar = "|"
	cooktimer_items = parse_config(self,Cooktimer_ItemFile)
	DishList = ""
	# make a new list for sorting case-insensitive
	for item in cooktimer_items:
		DishList = DishList + item + '|' + cooktimer_items[item] + "\n"
	contentsList = DishList.split('\n')
	contentsList = contentsList[:-1]
	contentsList.sort(lambda a, b: cmp(a.upper(), b.upper()))
	for dish in contentsList:
		item, value  = dish.split(OptionChar,1)
		self.gerechten.append([item,value])
	if Language == "nl_NL":
		self.gerechten[0][0] = "Kies gerecht"
	else:
		self.gerechten[0][0] = "Choose dish"
	font = QFont()
	font.setPointSize(48)
	startTime= QTime(0, 0, 0)  
	#
	self.gerechtButton1 = QComboBox(self)
	self.gerechtButton2 = QComboBox(self)
	self.gerechtButton3 = QComboBox(self)
	teller = 0
        for gerecht in self.gerechten:
		self.gerechtButton1.addItem(gerecht[0])
		self.gerechtButton2.addItem(gerecht[0])
		self.gerechtButton3.addItem(gerecht[0])


	# Center items in popup list
	self.gerechtButton1.setEditable(True)
        self.gerechtButton1.lineEdit().setAlignment(Qt.AlignCenter)  
        self.gerechtButton1.lineEdit().setReadOnly(True)
        self.gerechtButton1.lineEdit().setAlignment(Qt.AlignCenter)  
        for x in range(0,self.gerechtButton1.count()):
                self.gerechtButton1.setItemData(x, Qt.AlignCenter, Qt.TextAlignmentRole)
        self.gerechtButton1.setEditable(False)

	self.gerechtButton2.setEditable(True)
        self.gerechtButton2.lineEdit().setAlignment(Qt.AlignCenter)  
        self.gerechtButton2.lineEdit().setReadOnly(True)
        self.gerechtButton2.lineEdit().setAlignment(Qt.AlignCenter)  
        for x in range(0,self.gerechtButton2.count()):
                self.gerechtButton2.setItemData(x, Qt.AlignCenter, Qt.TextAlignmentRole)
        self.gerechtButton2.setEditable(False)

	self.gerechtButton3.setEditable(True)
        self.gerechtButton3.lineEdit().setAlignment(Qt.AlignCenter)  
        self.gerechtButton3.lineEdit().setReadOnly(True)
        self.gerechtButton3.lineEdit().setAlignment(Qt.AlignCenter)  
        for x in range(0,self.gerechtButton3.count()):
                self.gerechtButton3.setItemData(x, Qt.AlignCenter, Qt.TextAlignmentRole)
        self.gerechtButton3.setEditable(False)

	if Language == "nl_NL":
		self.timeButton1 = QMaemo5ValueButton("Kies (hh:mm)")
		self.timeButton2 = QMaemo5ValueButton("Kies (hh:mm)")
		self.timeButton3 = QMaemo5ValueButton("Kies (hh:mm)")
	else:
		self.timeButton1 = QMaemo5ValueButton("Pick (hh:mm)")
		self.timeButton2 = QMaemo5ValueButton("Pick (hh:mm)")
		self.timeButton3 = QMaemo5ValueButton("Pick (hh:mm)")
        self.selector1 = QMaemo5TimePickSelector()
	self.selector1.setCurrentTime(startTime)
        self.timeButton1.setPickSelector(self.selector1)
	self.timeButton1.setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
	self.timeButton1.setValueText("00:00:00")
	self.timeRemaining1 = QLabel("00:00:00")
	self.timeRemaining1.setStyleSheet("QLabel { background-color : #424242; color : white; }")
	self.timeRemaining1.setAlignment(Qt.AlignCenter)
	self.timeRemaining1.setLineWidth(3)
	self.timeRemaining1.setMidLineWidth(3)
	self.timeRemaining1.setFrameStyle(QFrame.Panel | QFrame.Sunken)
	self.timeRemaining1.setFont(font)

        self.selector2 = QMaemo5TimePickSelector()
	self.selector2.setCurrentTime(startTime)
        self.timeButton2.setPickSelector(self.selector2)
	self.timeButton2.setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
	self.timeButton2.setValueText("00:00:00")
	self.timeRemaining2 = QLabel("00:00:00")
	self.timeRemaining2.setStyleSheet("QLabel { background-color : #424242; color : white; }")
	self.timeRemaining2.setAlignment(Qt.AlignCenter)
	self.timeRemaining2.setLineWidth(3)
	self.timeRemaining2.setMidLineWidth(3)
	self.timeRemaining2.setFrameStyle(QFrame.Panel | QFrame.Sunken)
	self.timeRemaining2.setFont(font)

        self.selector3 = QMaemo5TimePickSelector()
	self.selector3.setCurrentTime(startTime)
        self.timeButton3.setPickSelector(self.selector3)
	self.timeButton3.setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
	self.timeButton3.setValueText("00:00:00")
	self.timeRemaining3 = QLabel("00:00:00")
	self.timeRemaining3.setStyleSheet("QLabel { background-color : #424242; color : white; }")
	self.timeRemaining3.setAlignment(Qt.AlignCenter)
	self.timeRemaining3.setLineWidth(3)
	self.timeRemaining3.setMidLineWidth(3)
	self.timeRemaining3.setFrameStyle(QFrame.Panel | QFrame.Sunken)
	self.timeRemaining3.setFont(font)

        self.startButton1 = QPushButton('Start')
        self.startButton2 = QPushButton('Start')
        self.startButton3 = QPushButton('Start')

        grid.addWidget(self.gerechtButton1,0,0)
        grid.addWidget(self.timeButton1,0,1)
        grid.addWidget(self.startButton1,0,2)
        grid.addWidget(self.timeRemaining1,1,0,1,3)

        grid.addWidget(self.gerechtButton2,2,0)
        grid.addWidget(self.timeButton2,2,1)
        grid.addWidget(self.startButton2,2,2)
        grid.addWidget(self.timeRemaining2,3,0,1,3)

        grid.addWidget(self.gerechtButton3,4,0)
        grid.addWidget(self.timeButton3,4,1)
        grid.addWidget(self.startButton3,4,2)
        grid.addWidget(self.timeRemaining3,5,0,1,3)

 
        # Let's make something happen when the button is pushed!
        self.connect(self.startButton1, SIGNAL("clicked()"), self.startTimer1)
        self.connect(self.startButton2, SIGNAL("clicked()"), self.startTimer2)
        self.connect(self.startButton3, SIGNAL("clicked()"), self.startTimer3)
        self.connect(self.gerechtButton1, SIGNAL("currentIndexChanged(int)"), self.setDefaultTime1)
        self.connect(self.gerechtButton2, SIGNAL("currentIndexChanged(int)"), self.setDefaultTime2)
        self.connect(self.gerechtButton3, SIGNAL("currentIndexChanged(int)"), self.setDefaultTime3)
        self.connect(self.timeButton1, SIGNAL("clicked()"), self.setPickedTime1)
        self.connect(self.timeButton2, SIGNAL("clicked()"), self.setPickedTime2)
        self.connect(self.timeButton3, SIGNAL("clicked()"), self.setPickedTime3)
 
        # Set the layout on the window: this means that our button will actually be displayed.
        self.setLayout(grid)
 
    def startTimer1(self):
	startTime1 = self.selector1.currentTime().toString("hh:mm:ss")
	if self.Timer1.isActive():
		self.Timer1.stop()
		self.timeRemaining1.setText(self.timeButton1.valueText())
        	self.startButton1.setText('Start')
	else:
		if startTime1 != "00:00:00":
			self.Timer1.start(1000)
			(h, m, s) = startTime1.split(':')
			self.startSecs1 = int(h) * 3600 + int(m) * 60 + int(s)
			self.timeRemaining1.setStyleSheet("QLabel { background-color : #424242; color : white; }")
        		self.startButton1.setText('Stop')
			

    def startTimer2(self):
	startTime2 = self.selector2.currentTime().toString("hh:mm:ss")
	if self.Timer2.isActive():
		self.Timer2.stop()
		self.timeRemaining2.setText(self.timeButton2.valueText())
        	self.startButton2.setText('Start')
	else:
		if startTime2 != "00:00:00":
			self.Timer2.start(1000)
			(h, m, s) = startTime2.split(':')
			self.startSecs2 = int(h) * 3600 + int(m) * 60 + int(s)
			self.timeRemaining2.setStyleSheet("QLabel { background-color : #424242; color : white; }")
	        	self.startButton2.setText('Stop')

    def startTimer3(self):
	startTime3 = self.selector3.currentTime().toString("hh:mm:ss")
	if self.Timer3.isActive():
		self.Timer3.stop()
		self.timeRemaining3.setText(self.timeButton3.valueText())
        	self.startButton3.setText('Start')
	else:
		if startTime3 != "00:00:00":
			self.Timer3.start(1000)
			(h, m, s ) = startTime3.split(':')
			self.startSecs3 = int(h) * 3600 + int(m) * 60 + int(s)
			self.timeRemaining3.setStyleSheet("QLabel { background-color : #424242; color : white; }")
	        	self.startButton3.setText('Stop')

    def updateTimer1(self):
	self.startSecs1 -=1
	hhmmss_format=format_seconds_to_hhmmss(self.startSecs1)
	self.timeRemaining1.setText(hhmmss_format)
	if self.startSecs1 == 0:
		self.Timer1.stop()
		self.timeRemaining1.setStyleSheet("QLabel { background-color : #8A0808; color : white; }")
		# set other alarm backgrounds to default
		self.timeRemaining2.setStyleSheet("QLabel { background-color : #424242; color : white; }")
		self.timeRemaining3.setStyleSheet("QLabel { background-color : #424242; color : white; }")
		Alarm(self)
	       	self.startButton1.setText('Start')

    def updateTimer2(self):
	self.startSecs2 -=1
	hhmmss_format=format_seconds_to_hhmmss(self.startSecs2)
	self.timeRemaining2.setText(hhmmss_format)
	if self.startSecs2 == 0:
		self.Timer2.stop()
		self.timeRemaining2.setStyleSheet("QLabel { background-color : #8A0808; color : white; }")
		# set other alarm backgrounds to default
		self.timeRemaining1.setStyleSheet("QLabel { background-color : #424242; color : white; }")
		self.timeRemaining3.setStyleSheet("QLabel { background-color : #424242; color : white; }")
		Alarm(self)
	       	self.startButton2.setText('Start')

    def updateTimer3(self):
	self.startSecs3 -=1
	hhmmss_format=format_seconds_to_hhmmss(self.startSecs3)
	self.timeRemaining3.setText(hhmmss_format)
	if self.startSecs3 == 0:
		self.Timer3.stop()
		self.timeRemaining3.setStyleSheet("QLabel { background-color : #8A0808; color : white; }")
		# set other alarm backgrounds to default
		self.timeRemaining1.setStyleSheet("QLabel { background-color : #424242; color : white; }")
		self.timeRemaining2.setStyleSheet("QLabel { background-color : #424242; color : white; }")
		Alarm(self)
	       	self.startButton3.setText('Start')

    def setDefaultTime1(self):
	self.timeButton1.setValueText(self.gerechten[self.gerechtButton1.currentIndex()][1])
	(h, m, s) = self.gerechten[self.gerechtButton1.currentIndex()][1].split(':')
	self.selector1.setCurrentTime(QTime(int(h),int(m),int(s)))
	self.timeButton1.setValueText(self.gerechten[self.gerechtButton1.currentIndex()][1])
	if not self.Timer1.isActive():
		self.timeRemaining1.setText(self.gerechten[self.gerechtButton1.currentIndex()][1])

    def setDefaultTime2(self):
	self.timeButton2.setValueText(self.gerechten[self.gerechtButton2.currentIndex()][1])
	(h, m, s) = self.gerechten[self.gerechtButton2.currentIndex()][1].split(':')
	self.selector2.setCurrentTime(QTime(int(h),int(m),int(s)))
	self.timeButton2.setValueText(self.gerechten[self.gerechtButton2.currentIndex()][1])
	if not self.Timer2.isActive():
		self.timeRemaining2.setText(self.gerechten[self.gerechtButton2.currentIndex()][1])

    def setDefaultTime3(self):
	self.timeButton3.setValueText(self.gerechten[self.gerechtButton3.currentIndex()][1])
	(h, m, s) = self.gerechten[self.gerechtButton3.currentIndex()][1].split(':')
	self.selector3.setCurrentTime(QTime(int(h),int(m),int(s)))
	self.timeButton3.setValueText(self.gerechten[self.gerechtButton3.currentIndex()][1])
	if not self.Timer3.isActive():
		self.timeRemaining3.setText(self.gerechten[self.gerechtButton3.currentIndex()][1])

    def setPickedTime1(self):
	self.timeButton1.setValueText(self.selector1.currentTime().toString("hh:mm:ss"))
	if not self.Timer1.isActive():
		self.timeRemaining1.setText(self.selector1.currentTime().toString("hh:mm:ss"))

    def setPickedTime2(self):
	self.timeButton2.setValueText(self.selector2.currentTime().toString("hh:mm:ss"))
	if not self.Timer2.isActive():
		self.timeRemaining2.setText(self.selector2.currentTime().toString("hh:mm:ss"))

    def setPickedTime3(self):
	self.timeButton3.setValueText(self.selector3.currentTime().toString("hh:mm:ss"))
	if not self.Timer3.isActive():
		self.timeRemaining3.setText(self.selector3.currentTime().toString("hh:mm:ss"))


 
if __name__ == '__main__':
    # QApplication controls things relating to a Qt application, like the main loop.
    # You should always instantiate it before using any QtGui related stuff.
    # See also:
    #   http://doc.trolltech.com/4.6/qapplication.html
    app = QApplication(sys.argv)
 
    # Create an instance (calling __init__, too, of course) of our window subclassing QWidget
    w = MyMainWindow()

    # Show our window
    w.show()
 
    # Main event loop of Qt. This won't return until the program exits.
    app.exec_()
    sys.exit()
