#!/usr/bin/env python

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

# GmailScreenlet (c) Whise <helder.fraga@hotmail.com>



import screenlets
from screenlets.options import StringOption, IntOption, AccountOption
import cairo
import pango
import gtk
from os import system
from os import path
import gobject
from screenlets import DefaultMenuItem
from screenlets import Plugins
mail = Plugins.importAPI('Mail')

#use gettext for translation
import gettext

_ = screenlets.utils.get_translator(__file__)

def tdoc(obj):
	obj.__doc__ = _(obj.__doc__)
	return obj

@tdoc

class GmailScreenlet(screenlets.Screenlet):
	"""A screenlet that shows your unread gmail message count, click on the mail icon to go to gmail.com"""
	
	# default meta-info for Screenlets
	__name__ = 'GmailScreenlet'
	__version__ = '0.7.2'
	__author__ = 'Helder Fraga'
	__desc__ =__doc__

	# a list of the converter class objects



	__timeout = None
	update_interval = 60
	forecast = ''
	msgs = ' 0'
	account = ('', '')	
	state_file_name = ''
	machine_state_file_names = [
		'/sys/devices/virtual/leds/asus:mail/brightness',
		'/proc/acpi/asus/mled',
		'/proc/driver/acerhk/led'
		]

	# constructor
	def __init__(self, **keyword_args):
		#call super
		screenlets.Screenlet.__init__(self, width=275, height=242, uses_theme=True,	**keyword_args)
		# set theme
		self.theme_name = "default"
		#add option groups
		self.add_options_group(_('Advanced'), _('Advanced settings.'))
		# add default menu items
		self.add_options_group(_('Gmail'), _('Gmail Screenlet settings ...'))
		self.add_option(IntOption(_('Gmail'), 'update_interval', 
			self.update_interval, _('Update interval'), _('The interval for updating info (in seconds ,3660 = 1 day, 25620 = 1 week)'), min=30, max=25620))
		self.add_option(AccountOption(_('Gmail'), 'account', 
			self.account, _('Username/Password'), 
			_('Enter username/password here ...')))
		self.add_option(StringOption(_('Advanced'),'state_file_name', self.get_state_file(), 
			_('State file name'), _('If set, then the number of unread messages in the Inbox will be written to this file when the screenlet updates. By default, this screenlet tries to locate a suitable LED control file.')))

		self.update_interval = self.update_interval

	def __setattr__(self, name, value):
		# call Screenlet.__setattr__ in baseclass (ESSENTIAL!!!!)
		screenlets.Screenlet.__setattr__(self, name, value)
		if name == 'account':
			self.update()

		if name == "update_interval":
			if value > 0:
				self.__dict__['update_interval'] = value
				if self.__timeout:
					gobject.source_remove(self.__timeout)
				self.__timeout = gobject.timeout_add(int(value * 1000), self.update)

			else:
				self.__dict__['update_interval'] = 1

	def on_init (self):
		print "Screenlet has been initialized."
		# add default menuitems
		self.add_default_menuitems(DefaultMenuItem.XML)
		self.add_default_menuitems()

	def update(self):
		self.check()
		self.redraw_canvas()
		return True

	def check(self):
		if self.account[0] != '' and self.account[1] != '':
			n = self.account[0].replace('@gmail.com','')
			try:
				self.msgs = mail.get_GMail_Num(n, self.account[1])
				print str(self.msgs) + ' Unread Messages'
			except:self.msgs = 0
		else:
			self.msgs = 0

		self.update_state_file()

	def update_state_file(self):
		print 'Mail state file: ' + self.state_file_name

		if not self.state_file_name:
			self.hide_notification()
			return False

		if path.exists(self.state_file_name):
			self.hide_notification()
			led_file = open(self.state_file_name, "w")
			if int(self.msgs) > 0:
				led_file.write(str(self.msgs))
			else:
				led_file.write("0")
			led_file.close()
		else:
			self.show_notification(_("The mail state file ") +
					self.state_file_name +
					_(" does not exist."))

	def get_state_file(self):
		for state_file in self.machine_state_file_names:
			print "Checking LED control file " + state_file
			if path.exists(state_file):
				print 'Found LED control file ' + state_file
				return state_file
		return ''

	def on_mouse_down(self, event):
		# filter events
		if event.button != 1 or event.type != gtk.gdk.BUTTON_PRESS:
			return False
		# recalculate cursor position
		x = event.x / self.scale
		y = event.y / self.scale
		# compute space between fields
		n = 1
		m = 10
		# find if a click occured over some field...
		if x >= 50 and x <= 190:
			if y >= m and y <= 100:
				d = y - m
				if d % (20 + m) <= 20:
					self.redraw_canvas()
					return True
		if x >= 180 and y >= 180 :
			system('xdg-open http://mail.google.com/mail/')
		return False


	def on_draw(self, ctx):
		ctx.scale(self.scale, self.scale)
		# render background
		self.theme.render(ctx, 'gmail')
	

		if self.msgs == None: self.msgs = 0
		if int(self.msgs) < 10:
			s = 36
			x,y = (188, 182)
		elif int(self.msgs) >= 10 and int(self.msgs) <= 99:
			s = 30
			x,y =(180, 187)
		elif int(self.msgs) >= 100 and int(self.msgs) <= 999:
			s = 24
			x,y =(175, 187)
		elif int(self.msgs) >= 1000:
			s = 20
			ctx.translate(170, 190)
		else:
			s = 36
			x,y = (188, 182)

		ctx.set_source_rgba(1, 1, 1, 0.9)
		self.draw_text(ctx,'<b>'+ str(self.msgs) +'</b>',x,y, 'FreeSans',s, self.width)
		
	def on_draw_shape(self, ctx):
		if self.theme:
			ctx.scale(self.scale, self.scale)

			self.theme.render(ctx, 'gmail')

	def on_menuitem_select (self, id):
		"""handle MenuItem-events in right-click menu"""
		if id == "update":
			self.check()
			self.redraw_canvas()


# If the program is run directly or passed as an argument to the python
# interpreter then create a Screenlet instance and show it
if __name__ == "__main__":
	import screenlets.session
	screenlets.session.create_session(GmailScreenlet)
