#!/usr/bin/python
#
# 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
 
# 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

####################
# Global variables #
####################
CooktimerVersion = "0.0.3-5"
Vibration = True
Sound = True
Wakeup = True
Orientation = "auto"
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"
hoursPicked0 = "00"
minutesPicked0 = "00"
secondsPicked0 = "00"
hoursPicked1 = "00"
minutesPicked1 = "00"
secondsPicked1 = "00"
hoursPicked2 = "00"
minutesPicked2 = "00"
secondsPicked2 = "00"
hoursPicked3 = "00"
minutesPicked3 = "00"
secondsPicked3 = "00"
dishName1 = ""
dishPicked1Nbr = ""
dishName2 = ""
dishPicked2Nbr = ""
dishName3 = ""
dishPicked3Nbr = ""
pause1 = False
pause2 = False
pause3 = False
currSelector = 0
playerPid = "99999"

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 load_dishes(self):
	global OptionChar
	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()))
	# initialize array
	dishes = []
	for dish in contentsList:
		item, value  = dish.split(OptionChar,1)
		dishes.append([item,value])
	return dishes

def Alarm(self):
	global playerPid
	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:
		player_call = subprocess.Popen([Player, "/opt/cooktimer/alarm-cooktimer.wav"]) # call subprocess
		playerPid = player_call.pid

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)
	global Orientation
	# 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("orientation auto\n")
			newConfigFile.write("sound true\n")
			newConfigFile.close()
	else:
		keepbacklightset = False
		vibrationset = False
		wakeupset = False
		soundset = False
		orientationset = 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
			if 'orientation' in line:
				orientationset = True
		ConfigFile.close()
		if not keepbacklightset or not vibrationset or not wakeupset or not soundset or not orientationset:
			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")
			if not orientationset:
				ConfigFile.write("orientation auto\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 orientation #
	###################
	Orientation = self.cooktimer_opts["orientation"]
	if Orientation == "portrait":
		self.setAttribute(Qt.WA_Maemo5PortraitOrientation, True)
	elif Orientation == "landscape":
		self.setAttribute(Qt.WA_Maemo5LandscapeOrientation, True)
	else:
		self.setAttribute(Qt.WA_Maemo5AutoOrientation, True)
	##############
	# 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 #
	###############
	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.orientationAction = QAction( '', self)
	if self.cooktimer_opts["orientation"] == "portrait":
		self.orientationAction.setText("Set auto orientation")
	elif self.cooktimer_opts["orientation"] == "landscape":
		self.orientationAction.setText("Lock portrait")
	else:
		self.orientationAction.setText("Lock landscape")

	editAction = QAction( '&Edit items', self)
	aboutAction = QAction( '&About', self)

	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(self.orientationAction)
	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)
	self.orientationAction.triggered.connect(self.orientationPushed)
	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())-1)*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 saveSettings(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"
	if self.soundAction.isChecked():
		self.cooktimer_opts["sound"] = "true"
	else: self.cooktimer_opts["sound"] = "false"
	self.cooktimer_opts["orientation"] = Orientation
	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 successfully 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 wakeupPushed(self):
	global Wakeup
	if self.wakeupAction.isChecked():
		Wakeup = True
	else:
		Wakeup = False
	self.saveSettings()

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

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

    def soundPushed(self):
	global Sound
	if self.soundAction.isChecked():
		Sound = True
	else:
		Sound = False
	self.saveSettings()
	
    def orientationPushed(self):
	global Orientation
	if Orientation == "auto":
		Orientation = "landscape"
		self.setAttribute(Qt.WA_Maemo5LandscapeOrientation, True)
		self.orientationAction.setText("Lock portrait")
	elif Orientation == "landscape":
		Orientation = "portrait"
		self.setAttribute(Qt.WA_Maemo5PortraitOrientation, True)
		self.orientationAction.setText("Set auto orientation")
	elif Orientation == "portrait":
		Orientation = "auto"
		self.setAttribute(Qt.WA_Maemo5AutoOrientation, True)
		self.orientationAction.setText("Lock landscape")
	self.saveSettings()
	
    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>Version "+CooktimerVersion+"</center>"),1)
	verticalLayout.addWidget(QLabel("<center>Created by Arno Dekker (ade)</center>"),2)
	vbox.addLayout (verticalLayout)
	d.setLayout(vbox)
	d.show()


class itemWindow(QWidget):
    def __init__(self,parent):
	super(itemWindow, self).__init__(parent)
	self.wg = QDialog(self)
	if Language == "nl_NL":
		self.wg.setWindowTitle("Gerecht kooktijden")
	else:
		self.wg.setWindowTitle("Dish cooktimes")

	# create a scroll area for the modules to load
	global OptionChar
	grid2 = QGridLayout()
	grid = QGridLayout()
	scrollingWidget = QWidget()
	scrollingWidget.setLayout(grid2)
	 
	self.myScrollArea = QScrollArea()
	self.myScrollArea.setWidgetResizable(True)
	self.myScrollArea.setEnabled(True)
	 
	self.myScrollArea.setWidget(scrollingWidget)
        hbox = QGridLayout()
	hbox.addWidget(self.myScrollArea)
	 
	self.wg.setMinimumHeight(1050)
	self.wg.setMaximumHeight(1050)
	# Layout
        grid = QGridLayout()
        self.wg.setLayout(hbox)
	grid2.setColumnMinimumWidth(0,150)
	grid.setHorizontalSpacing(0)
	grid.setVerticalSpacing(0)
	self.saveItemButton = QPushButton("SAVE",self)
	self.saveItemButton.setStyleSheet(
	"QPushButton { color: red; font:bold; }"
		)
        hbox.addWidget(self.saveItemButton,17,0,1,3)
	OptionChar =  '|'
	cooktimer_items = parse_config(self,Cooktimer_ItemFile)
	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()))
	signalMapper = QSignalMapper(self) ;
	for dish in contentsList:
		item, value  = dish.split('|',1)
		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)
		grid2.addWidget(globals()['ItemName%s' % var_num],teller,0)
		if Language == "nl_NL":
			globals()['timeSel%s' % var_num] = QMaemo5ValueButton("tijd")
		else:
			globals()['timeSel%s' % var_num] = QMaemo5ValueButton("time")
		globals()['timeSel%s' % var_num].setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
		globals()['timeSel%s' % var_num].setValueText(hh+":"+mi+":"+ss)
		grid2.addWidget(globals()['timeSel%s' % var_num], teller, 1)
		signalMapper.setMapping(globals()['timeSel%s' % var_num],str(var_num))
        	self.connect(globals()['timeSel%s' % var_num], SIGNAL("clicked()"), signalMapper, SLOT("map()"))
		globals()['clearButton%s' % var_num] = QPushButton()
		globals()['clearButton%s' % var_num].setIcon(QIcon.fromTheme("general_close"))
		globals()['clearButton%s' % var_num].setStyleSheet("background: transparent; border: none")
		grid2.addWidget(globals()['clearButton%s' % var_num], teller, 2)
		signalMapper.setMapping(globals()['clearButton%s' % var_num],var_num)
		self.connect(globals()['clearButton%s' % var_num], SIGNAL("clicked()"), signalMapper, SLOT("map()"))
		teller +=1
		var_num +=1

	for count in range(teller,52):
		globals()['ItemName%s' % var_num] = QLineEdit()
		globals()['ItemName%s' % var_num].setMaxLength(maxLen)
		grid2.addWidget(globals()['ItemName%s' % var_num],teller,0)
		if Language == "nl_NL":
			globals()['timeSel%s' % var_num] = QMaemo5ValueButton("tijd")
		else:
			globals()['timeSel%s' % var_num] = QMaemo5ValueButton("time")
		globals()['timeSel%s' % var_num].setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
		globals()['timeSel%s' % var_num].setValueText("00:00:00")
		grid2.addWidget(globals()['timeSel%s' % var_num], teller, 1)
		signalMapper.setMapping(globals()['timeSel%s' % var_num],str(var_num))
        	self.connect(globals()['timeSel%s' % var_num], SIGNAL("clicked()"), signalMapper, SLOT("map()"))
		globals()['clearButton%s' % var_num] = QPushButton()
		globals()['clearButton%s' % var_num].setIcon(QIcon.fromTheme("general_close"))
		globals()['clearButton%s' % var_num].setStyleSheet("background: transparent; border: none")
		grid2.addWidget(globals()['clearButton%s' % var_num], teller, 2)
		signalMapper.setMapping(globals()['clearButton%s' % var_num],var_num)
		self.connect(globals()['clearButton%s' % var_num], SIGNAL("clicked()"), signalMapper, SLOT("map()"))
		teller +=1
		var_num +=1

	self.connect(signalMapper, SIGNAL("mapped(int)"), self.Clear)
	self.connect(signalMapper, SIGNAL("mapped(const QString &)"), self.TimeSel)

	self.connect(QApplication.desktop(), SIGNAL("resized(int)"), self.orientationChanged)
	self.connect(self.saveItemButton, SIGNAL("clicked()"),self.Saveitems)

        self.wg.exec_()

    def Clear(self,waarde):
	global secondsPicked0
	global minutesPicked0
	global hoursPicked0
	globals()['ItemName%s' % waarde].clear()
	globals()['timeSel%s' % waarde].setValueText("00:00:00")

    def TimeSel(self,waarde):
	global secondsPicked0
	global minutesPicked0
	global hoursPicked0
	global currSelector

	currSelector = 0
	hh_mi_ss = globals()['timeSel%s' % waarde].valueText().split(':',2)
	hoursPicked0 = hh_mi_ss[0]
	minutesPicked0 = hh_mi_ss[1]
	secondsPicked0 = hh_mi_ss[2]

	timePick = TimePickDialog(self)
	timePick.show()  
	hours = '%02d' % int(hoursPicked0)
	minutes = '%02d' % int(minutesPicked0)
	seconds = '%02d' % int(secondsPicked0)
        timestring = hours + ":" + minutes + ":" + seconds
	globals()['timeSel%s' % waarde].setValueText(timestring)

    def orientationChanged(self):
        screenGeometry = QApplication.desktop().screenGeometry()
        if screenGeometry.width() > screenGeometry.height():
                # landscape
		self.wg.resize(750,300)
		self.wg.setMinimumHeight(440)
		self.wg.setMaximumHeight(440)
		self.myScrollArea.resize(750,300)
		self.myScrollArea.setMinimumHeight(300)
		self.myScrollArea.setMaximumHeight(300)
        else:
                # portrait
		self.wg.resize(430,680)
		self.wg.setMinimumHeight(1050)
		self.wg.setMaximumHeight(1050)
		self.myScrollArea.resize(400,680)
		self.myScrollArea.setMaximumHeight(630)
		self.myScrollArea.setMinimumHeight(630)

    def Saveitems(self):
	try:
		newItemFile = open(Cooktimer_ItemFile,"w")
	except:
		QMessageBox.critical(self, "Warning",  "Cannot write " + Cooktimer_ItemFile)	
	else:
		for count in range(1,51):
			if globals()['ItemName%s' % count ].text() != "": 
				newItemFile.write(globals()['ItemName%s' % count ].text() + "|" + \
				globals()['timeSel%s' % count].valueText() + "\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:"Items are successfully saved"')
        self.wg.close()



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
        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)
 
	font = QFont()
	font.setPointSize(48)
	startTime= QTime(0, 0, 0)  

	if Language == "nl_NL":
		self.gerechtButton1 = QPushButton("Kies gerecht")
		self.gerechtButton2 = QPushButton("Kies gerecht")
		self.gerechtButton3 = QPushButton("Kies gerecht")
		self.timeButton1 = QMaemo5ValueButton("Kies tijd")
		self.timeButton2 = QMaemo5ValueButton("Kies tijd")
		self.timeButton3 = QMaemo5ValueButton("Kies tijd")
	else:
		self.gerechtButton1 = QPushButton("Choose dish")
		self.gerechtButton2 = QPushButton("Choose dish")
		self.gerechtButton3 = QPushButton("Choose dish")
		self.timeButton1 = QMaemo5ValueButton("Pick duration")
		self.timeButton2 = QMaemo5ValueButton("Pick duration")
		self.timeButton3 = QMaemo5ValueButton("Pick duration")

	self.initDishText = self.gerechtButton1.text()
	self.timeButton1.setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
	self.timeButton1.setValueText("00:00:00")
	self.timeRemaining1 = QPushButton("00:00:00")
	self.timeRemaining1.setStyleSheet("background: transparent; border: none")
	self.timeRemaining1.setFont(font)

	self.timeButton2.setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
	self.timeButton2.setValueText("00:00:00")
	self.timeRemaining2 = QPushButton("00:00:00")
	self.timeRemaining2.setStyleSheet("background: transparent; border: none")
	self.timeRemaining2.setFont(font)

	self.timeButton3.setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
	self.timeButton3.setValueText("00:00:00")
	self.timeRemaining3 = QPushButton("00:00:00")
	self.timeRemaining3.setStyleSheet("background: transparent; border: none")
	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)

	# Disable startbuttons by default
	self.startButton1.setEnabled(False)
	self.startButton2.setEnabled(False)
	self.startButton3.setEnabled(False)
	self.timeRemaining1.setEnabled(False)
	self.timeRemaining2.setEnabled(False)
	self.timeRemaining3.setEnabled(False)
 
        # 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("clicked()"), self.setDefaultTime1)
        self.connect(self.gerechtButton2, SIGNAL("clicked()"), self.setDefaultTime2)
        self.connect(self.gerechtButton3, SIGNAL("clicked()"), 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)
        self.connect(self.timeRemaining1, SIGNAL("clicked()"), self.togglePause1)
        self.connect(self.timeRemaining2, SIGNAL("clicked()"), self.togglePause2)
        self.connect(self.timeRemaining3, SIGNAL("clicked()"), self.togglePause3)
 
        # Set the layout on the window: this means that our button will actually be displayed.
        self.setLayout(grid)
 
    def startTimer1(self):
	global secondsPicked1
	global minutesPicked1
	global hoursPicked1
	global pause1
	startTime1 = str('%02d'  % int(hoursPicked1)) + ":" + str('%02d' % int(minutesPicked1)) + ":" + str('%02d' % int(secondsPicked1))
	if self.Timer1.isActive() or pause1:
		self.Timer1.stop()
		pause1 = False
		self.timeRemaining1.setEnabled(False)
		self.timeRemaining1.setText(self.timeButton1.valueText())
        	self.startButton1.setText('Start')
		self.timeRemaining1.setStyleSheet("background: transparent; border: none")
		if startTime1 ==  "00:00:00":
			self.startButton1.setEnabled(False)
	else:
		if startTime1 != "00:00:00":
			self.Timer1.start(1000)
			self.timeRemaining1.setEnabled(True)
			(h, m, s) = startTime1.split(':')
			self.startSecs1 = int(h) * 3600 + int(m) * 60 + int(s)
			self.timeRemaining1.setStyleSheet("QPushButton { background-color : #21610B; color : white; }")
        		self.startButton1.setText('Stop')

    def startTimer2(self):
	global secondsPicked2
	global minutesPicked2
	global hoursPicked2
	global pause2
	startTime2 = str('%02d'  % int(hoursPicked2)) + ":" + str('%02d' % int(minutesPicked2)) + ":" + str('%02d' % int(secondsPicked2))
	if self.Timer2.isActive() or pause2:
		self.Timer2.stop()
		pause2 = False
		self.timeRemaining2.setEnabled(False)
		self.timeRemaining2.setText(self.timeButton2.valueText())
        	self.startButton2.setText('Start')
		self.timeRemaining2.setStyleSheet("background: transparent; border: none")
		if startTime2 ==  "00:00:00":
			self.startButton2.setEnabled(False)
	else:
		if startTime2 != "00:00:00":
			self.Timer2.start(1000)
			self.timeRemaining2.setEnabled(True)
			(h, m, s) = startTime2.split(':')
			self.startSecs2 = int(h) * 3600 + int(m) * 60 + int(s)
			self.timeRemaining2.setStyleSheet("QPushButton { background-color : #21610B; color : white; }")
        		self.startButton2.setText('Stop')

    def startTimer3(self):
	global secondsPicked3
	global minutesPicked3
	global hoursPicked3
	global pause3
	startTime3 = str('%02d'  % int(hoursPicked3)) + ":" + str('%02d' % int(minutesPicked3)) + ":" + str('%02d' % int(secondsPicked3))
	if self.Timer3.isActive() or pause3:
		self.Timer3.stop()
		pause3 = False
		self.timeRemaining3.setEnabled(False)
		self.timeRemaining3.setText(self.timeButton3.valueText())
        	self.startButton3.setText('Start')
		self.timeRemaining3.setStyleSheet("background: transparent; border: none")
		if startTime3 ==  "00:00:00":
			self.startButton3.setEnabled(False)
	else:
		if startTime3 != "00:00:00":
			self.Timer3.start(1000)
			self.timeRemaining3.setEnabled(True)
			(h, m, s) = startTime3.split(':')
			self.startSecs3 = int(h) * 3600 + int(m) * 60 + int(s)
			self.timeRemaining3.setStyleSheet("QPushButton { background-color : #21610B; 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("QPushButton { background-color : #8A0808; color : white; }")

		if not pause2:
			if self.Timer2.isActive():
				self.timeRemaining2.setStyleSheet("QPushButton { background-color : #21610B; color : white; }")
			else:
				self.timeRemaining2.setStyleSheet("background: transparent; border: none")
				self.timeRemaining2.setEnabled(False)
		if not pause3:
			if self.Timer3.isActive():
				self.timeRemaining3.setStyleSheet("QPushButton { background-color : #21610B; color : white; }")
			else:
				self.timeRemaining3.setStyleSheet("background: transparent; border: none")
				self.timeRemaining3.setEnabled(False)
		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("QPushButton { background-color : #8A0808; color : white; }")
		# set other alarm backgrounds to default
		if not pause1:
			if self.Timer1.isActive():
				self.timeRemaining1.setStyleSheet("QPushButton { background-color : #21610B; color : white; }")
			else:
				self.timeRemaining1.setStyleSheet("background: transparent; border: none")
				self.timeRemaining1.setEnabled(False)
		if not pause3:
			if self.Timer3.isActive():
				self.timeRemaining3.setStyleSheet("QPushButton { background-color : #21610B; color : white; }")
			else:
				self.timeRemaining3.setStyleSheet("background: transparent; border: none")
				self.timeRemaining3.setEnabled(False)
		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("QPushButton { background-color : #8A0808; color : white; }")
		# set other alarm backgrounds to default
		if not pause1:
			if self.Timer1.isActive():
				self.timeRemaining1.setStyleSheet("QPushButton { background-color : #21610B; color : white; }")
			else:
				self.timeRemaining1.setStyleSheet("background: transparent; border: none")
				self.timeRemaining1.setEnabled(False)
		if not pause2:
			if self.Timer2.isActive():
				self.timeRemaining2.setStyleSheet("QPushButton { background-color : #21610B; color : white; }")
			else:
				self.timeRemaining2.setStyleSheet("background: transparent; border: none")
				self.timeRemaining2.setEnabled(False)
		Alarm(self)
	       	self.startButton3.setText('Start')

    def setDefaultTime1(self):
	global secondsPicked1
	global minutesPicked1
	global hoursPicked1
	global dishName1
	global currSelector

	currSelector = 1
	dishPick = DishPickDialog(self)
	dishPick.show()
	if dishName1:
		self.gerechtButton1.setText(dishName1)
		dish_items = load_dishes(self)
		(hoursPicked1, minutesPicked1, secondsPicked1) = dish_items[dishPicked1Nbr][1].split(':')
		hours = '%02d' % int(hoursPicked1)
		minutes = '%02d' % int(minutesPicked1)
		seconds = '%02d' % int(secondsPicked1)
		timestring = hours + ":" + minutes + ":" + seconds
		self.timeButton1.setValueText(timestring)
		if not self.Timer1.isActive() and not pause1:
			self.timeRemaining1.setText(timestring)
			if timestring == "00:00:00":
				self.startButton1.setEnabled(False)
			else:
				self.startButton1.setEnabled(True)
	# clear it again
	dishName1 = ""

    def setDefaultTime2(self):
	global secondsPicked2
	global minutesPicked2
	global hoursPicked2
	global dishName2
	global currSelector

	currSelector = 2
	dishPick = DishPickDialog(self)
	dishPick.show()
	if dishName2:
		self.gerechtButton2.setText(dishName2)
		dish_items = load_dishes(self)
		(hoursPicked2, minutesPicked2, secondsPicked2) = dish_items[dishPicked2Nbr][1].split(':')
		hours = '%02d' % int(hoursPicked2)
		minutes = '%02d' % int(minutesPicked2)
		seconds = '%02d' % int(secondsPicked2)
		timestring = hours + ":" + minutes + ":" + seconds
		self.timeButton2.setValueText(timestring)
		if not self.Timer2.isActive() and not pause2:
			self.timeRemaining2.setText(timestring)
			if timestring == "00:00:00":
				self.startButton2.setEnabled(False)
			else:
				self.startButton2.setEnabled(True)
	# clear it again
	dishName2 = ""

    def setDefaultTime3(self):
	global secondsPicked3
	global minutesPicked3
	global hoursPicked3
	global dishName3
	global currSelector

	currSelector = 3
	dishPick = DishPickDialog(self)
	dishPick.show()
	if dishName3:
		self.gerechtButton3.setText(dishName3)
		dish_items = load_dishes(self)
		(hoursPicked3, minutesPicked3, secondsPicked3) = dish_items[dishPicked3Nbr][1].split(':')
		hours = '%02d' % int(hoursPicked3)
		minutes = '%02d' % int(minutesPicked3)
		seconds = '%02d' % int(secondsPicked3)
		timestring = hours + ":" + minutes + ":" + seconds
		self.timeButton3.setValueText(timestring)
		if not self.Timer3.isActive() and not pause3:
			self.timeRemaining3.setText(timestring)
			if timestring == "00:00:00":
				self.startButton3.setEnabled(False)
			else:
				self.startButton3.setEnabled(True)
	# clear it again
	dishName3 = ""

    def setPickedTime1(self):
	global secondsPicked1
	global minutesPicked1
	global hoursPicked1
	global currSelector
	global pause1
	currSelector = 1
	timePick = TimePickDialog(self)
	timePick.show()  
	hours = '%02d' % int(hoursPicked1)
	minutes = '%02d' % int(minutesPicked1)
	seconds = '%02d' % int(secondsPicked1)
        timestring = hours + ":" + minutes + ":" + seconds
	self.timeButton1.setValueText(timestring)
	if timestring == "00:00:00":
		self.gerechtButton1.setText(self.initDishText)
	if not self.Timer1.isActive() and not pause1:
		self.timeRemaining1.setText(timestring)
		if timestring == "00:00:00":
			self.startButton1.setEnabled(False)
		else:
			self.startButton1.setEnabled(True)

    def setPickedTime2(self):
	global secondsPicked2
	global minutesPicked2
	global hoursPicked2
	global currSelector
	global pause2
	currSelector = 2
	timePick = TimePickDialog(self)
	timePick.show()  
	hours = '%02d' % int(hoursPicked2)
	minutes = '%02d' % int(minutesPicked2)
	seconds = '%02d' % int(secondsPicked2)
        timestring = hours + ":" + minutes + ":" + seconds
	self.timeButton2.setValueText(timestring)
	if timestring == "00:00:00":
		self.gerechtButton2.setText(self.initDishText)
	if not self.Timer2.isActive() and not pause2:
		self.timeRemaining2.setText(timestring)
		if timestring == "00:00:00":
			self.startButton2.setEnabled(False)
		else:
			self.startButton2.setEnabled(True)

    def setPickedTime3(self):
	global secondsPicked3
	global minutesPicked3
	global hoursPicked3
	global currSelector
	global pause3
	currSelector = 3
	timePick = TimePickDialog(self)
	timePick.show()  
	hours = '%02d' % int(hoursPicked3)
	minutes = '%02d' % int(minutesPicked3)
	seconds = '%02d' % int(secondsPicked3)
        timestring = hours + ":" + minutes + ":" + seconds
	self.timeButton3.setValueText(timestring)
	if timestring == "00:00:00":
		self.gerechtButton3.setText(self.initDishText)
	if not self.Timer3.isActive() and not pause3:
		self.timeRemaining3.setText(timestring)
		if timestring == "00:00:00":
			self.startButton3.setEnabled(False)
		else:
			self.startButton3.setEnabled(True)

    def is_pid_running_on_unix(self,pid):
	try:
		# singal 0 is null signal, check for validity of the pid
		os.kill(pid, 0)
	except OSError:
		return False
	return True

    def togglePause1(self):
	global pause1
	if self.timeRemaining1.text() != "00:00:00":
		if self.Timer1.isActive():
			self.Timer1.stop()
			self.timeRemaining1.setStyleSheet("QPushButton { background-color : #FF6600; color : white; }")
			pause1 = True
		else:
			if pause1:
				self.Timer1.start()
				self.timeRemaining1.setStyleSheet("QPushButton { background-color : #21610B; color : white; }")
				pause1 = False
	elif Sound and self.is_pid_running_on_unix(playerPid) and playerPid != "99999":
		os.kill(int(playerPid), 15)

    def togglePause2(self):
	global pause2
	if self.timeRemaining2.text() != "00:00:00":
		if self.Timer2.isActive():
			self.Timer2.stop()
			self.timeRemaining2.setStyleSheet("QPushButton { background-color : #FF6600; color : white; }")
			pause2 = True
		else:
			if pause2:
				self.Timer2.start()
				self.timeRemaining2.setStyleSheet("QPushButton { background-color : #21610B; color : white; }")
				pause2 = False
	elif Sound and self.is_pid_running_on_unix(playerPid) and playerPid != "99999":
		os.kill(int(playerPid), 15)

    def togglePause3(self):
	global pause3
	if self.timeRemaining3.text() != "00:00:00":
		if self.Timer3.isActive():
			self.Timer3.stop()
			self.timeRemaining3.setStyleSheet("QPushButton { background-color : #FF6600; color : white; }")
			pause3 = True
		else:
			if pause3:
				self.Timer3.start()
				self.timeRemaining3.setStyleSheet("QPushButton { background-color : #21610B; color : white; }")
				pause3 = False
	elif Sound and self.is_pid_running_on_unix(playerPid) and playerPid != "99999":
		os.kill(int(playerPid), 15)

class TimePickDialog(QWidget):
    def __init__(self,parent):
        super(TimePickDialog, self).__init__(parent)
	self.d = QDialog(self)
	self.d.setMinimumHeight(680)
	self.d.setMaximumHeight(680)
	if Language == "nl_NL":
		self.d.setWindowTitle("uren | minuten | seconden")
        	doneButton = QPushButton(self.tr("Voltooid"))
	else:
		self.d.setWindowTitle("hours | minutes | seconds")
        	doneButton = QPushButton(self.tr("Done"))
	hbox = QGridLayout() 
	horizontalLayout = QGridLayout() 
	self.hourWidget = QListWidget()
	self.minuteWidget = QListWidget()
	self.secondWidget = QListWidget()
	f = QFont()
	f.setPointSize(24)
	global secondsPicked0
	global minutesPicked0
	global hoursPicked0
	global secondsPicked1
	global minutesPicked1
	global hoursPicked1
	global secondsPicked2
	global minutesPicked2
	global hoursPicked2
	global secondsPicked3
	global minutesPicked3
	global hoursPicked3
	global currSelector

	for i in range(49):
		item = QListWidgetItem("%02i" % i)
		item.setFont(f)
		item.setTextAlignment(Qt.AlignCenter)
		self.hourWidget.addItem(item)

	for i in range(60):
		item = QListWidgetItem("%02i" % i)
		item.setFont(f)
		item.setTextAlignment(Qt.AlignCenter)
		self.minuteWidget.addItem(item)

	for i in range(60):
		item = QListWidgetItem("%02i" % i)
		item.setFont(f)
		item.setTextAlignment(Qt.AlignCenter)
		self.secondWidget.addItem(item)

	# set time
	if currSelector == 0:
		self.hourWidget.setCurrentRow(int(hoursPicked0))
		self.minuteWidget.setCurrentRow(int(minutesPicked0))
		self.secondWidget.setCurrentRow(int(secondsPicked0))
	if currSelector == 1:
		self.hourWidget.setCurrentRow(int(hoursPicked1))
		self.minuteWidget.setCurrentRow(int(minutesPicked1))
		self.secondWidget.setCurrentRow(int(secondsPicked1))
	if currSelector == 2:
		self.hourWidget.setCurrentRow(int(hoursPicked2))
		self.minuteWidget.setCurrentRow(int(minutesPicked2))
		self.secondWidget.setCurrentRow(int(secondsPicked2))
	if currSelector == 3:
		self.hourWidget.setCurrentRow(int(hoursPicked3))
		self.minuteWidget.setCurrentRow(int(minutesPicked3))
		self.secondWidget.setCurrentRow(int(secondsPicked3))

	horizontalLayout.addWidget(self.hourWidget,0,0) 
	horizontalLayout.addWidget(self.minuteWidget,0,1) 
	horizontalLayout.addWidget(self.secondWidget,0,2) 
        screenGeometry = QApplication.desktop().screenGeometry()
        if screenGeometry.width() > screenGeometry.height():
                # landscape
		self.hourWidget.scrollToItem(self.hourWidget.currentItem(),QAbstractItemView.PositionAtTop)
		self.minuteWidget.scrollToItem(self.minuteWidget.currentItem(),QAbstractItemView.PositionAtTop)
		self.secondWidget.scrollToItem(self.secondWidget.currentItem(),QAbstractItemView.PositionAtTop)
        else:
                # portrait
		self.hourWidget.scrollToItem(self.hourWidget.currentItem(),QAbstractItemView.PositionAtCenter)
		self.minuteWidget.scrollToItem(self.minuteWidget.currentItem(),QAbstractItemView.PositionAtCenter)
		self.secondWidget.scrollToItem(self.secondWidget.currentItem(),QAbstractItemView.PositionAtCenter)
	self.connect(QApplication.desktop(), SIGNAL("resized(int)"), self.orientationChanged)
	buttonBox = QDialogButtonBox()
	horizontalLayout.addWidget(doneButton,1,0,1,3)
	self.d.setLayout(hbox)
	hbox.addLayout (horizontalLayout,0,0)
	self.connect(doneButton, SIGNAL("clicked()"), self.accept)
	self.d.exec_()

    def accept(self):
	global secondsPicked0
	global minutesPicked0
	global hoursPicked0
	global secondsPicked1
	global minutesPicked1
	global hoursPicked1
	global secondsPicked2
	global minutesPicked2
	global hoursPicked2
	global secondsPicked3
	global minutesPicked3
	global hoursPicked3
	global currSelector
	if currSelector == 0:
		hoursPicked0 = self.hourWidget.currentRow()
		minutesPicked0 = self.minuteWidget.currentRow()
		secondsPicked0 = self.secondWidget.currentRow()
	if currSelector == 1:
		hoursPicked1 = self.hourWidget.currentRow()
		minutesPicked1 = self.minuteWidget.currentRow()
		secondsPicked1 = self.secondWidget.currentRow()
	if currSelector == 2:
		hoursPicked2 = self.hourWidget.currentRow()
		minutesPicked2 = self.minuteWidget.currentRow()
		secondsPicked2 = self.secondWidget.currentRow()
	if currSelector == 3:
		hoursPicked3 = self.hourWidget.currentRow()
		minutesPicked3 = self.minuteWidget.currentRow()
		secondsPicked3 = self.secondWidget.currentRow()
	self.d.close()

    def orientationChanged(self):
        screenGeometry = QApplication.desktop().screenGeometry()
        if screenGeometry.width() > screenGeometry.height():
                # landscape
		self.d.setMinimumHeight(680)
		self.d.setMaximumHeight(680)
		self.hourWidget.scrollToItem(self.hourWidget.currentItem(),QAbstractItemView.PositionAtTop)
		self.minuteWidget.scrollToItem(self.minuteWidget.currentItem(),QAbstractItemView.PositionAtTop)
		self.secondWidget.scrollToItem(self.secondWidget.currentItem(),QAbstractItemView.PositionAtTop)
        else:
                # portrait
                self.d.resize(680,740)
		self.d.setMinimumHeight(680)
		self.d.setMaximumHeight(680)
		self.hourWidget.scrollToItem(self.hourWidget.currentItem(),QAbstractItemView.PositionAtCenter)
		self.minuteWidget.scrollToItem(self.minuteWidget.currentItem(),QAbstractItemView.PositionAtCenter)
		self.secondWidget.scrollToItem(self.secondWidget.currentItem(),QAbstractItemView.PositionAtCenter)


class DishPickDialog(QWidget):
    def __init__(self,parent):
        super(DishPickDialog, self).__init__(parent)
	self.d = QDialog(self)
	self.d.setMinimumHeight(680)
	self.d.setMaximumHeight(680)
	if Language == "nl_NL":
		self.d.setWindowTitle("Kies gerecht")
	else:
		self.d.setWindowTitle("Choose dish")
	hbox = QGridLayout() 
	horizontalLayout = QGridLayout() 
	self.dishWidget = QListWidget()

	dish_items = load_dishes(self)

        for gerecht in dish_items:
		item = QListWidgetItem(gerecht[0])
		item.setTextAlignment(Qt.AlignCenter)
		self.dishWidget.addItem(item)

	horizontalLayout.addWidget(self.dishWidget,0,0) 
        screenGeometry = QApplication.desktop().screenGeometry()

	self.connect(QApplication.desktop(), SIGNAL("resized(int)"), self.orientationChanged)
	self.d.setLayout(hbox)
	hbox.addLayout (horizontalLayout,0,0)

        self.connect(self.dishWidget, SIGNAL("itemClicked(QListWidgetItem *)"), self.itemClicked)
	self.d.exec_()

    def itemClicked(self, item):
	global currSelector
	global dishName1
	global dishPicked1Nbr
	global dishName2
	global dishPicked2Nbr
	global dishName3
	global dishPicked3Nbr
	if currSelector == 1:
		dishPicked1Nbr = self.dishWidget.currentRow()
		dishName1 = item.text()
	if currSelector == 2:
		dishPicked2Nbr = self.dishWidget.currentRow()
		dishName2 = item.text()
	if currSelector == 3:
		dishPicked3Nbr = self.dishWidget.currentRow()
		dishName3 = item.text()
	self.d.close()

    def orientationChanged(self):
        screenGeometry = QApplication.desktop().screenGeometry()
        if screenGeometry.width() > screenGeometry.height():
                # landscape
		self.d.setMinimumHeight(680)
		self.d.setMaximumHeight(680)
		self.dishWidget.scrollToItem(self.dishWidget.currentItem(),QAbstractItemView.PositionAtTop)
        else:
                # portrait
                self.d.resize(680,740)
		self.d.setMinimumHeight(680)
		self.d.setMaximumHeight(680)
		self.dishWidget.scrollToItem(self.dishWidget.currentItem(),QAbstractItemView.PositionAtCenter)
 
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()
