#!/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/>.

#  AgeExtended by Chrigi Schmid 2009
#
# INFO:
# - Shows your age not only in years but also in
#   - days
#   - hours
#   - minutes
#   - seconds
# 
# CHANGELOG:
# v0.1:
# - initial version

import screenlets
from screenlets.options import StringOption
import pango
import time
import gobject
import locale
#use gettext for translation
import gettext

_ = screenlets.utils.get_translator(__file__)

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

@tdoc

class AgeExtendedScreenlet(screenlets.Screenlet):
	"""Display your age in seconds, minutes, hours and days"""
	
	# default meta-info for Screenlets
	__name__ = 'AgeExtendedScreenlet'
	__version__ = '0.2'
	__author__ = 'Chrigi Schmid'
	__desc__ = __doc__

	# internals
	__timeout = None
	p_layout = None
	# editable options and defaults
	__update_interval = 1 # every second
	text = "Anonymus"
	born_date = "1932-02-09 18:20:00"
		
	# constructor
	def __init__(self, **keyword_args):
		# call super
		screenlets.Screenlet.__init__(self, uses_theme=True,width=300, height=150, **keyword_args)
		# set theme
		self.theme_name = "default"
		
		# add option groups
		self.add_options_group(_('AgeExtended'), _('AgeExtended settings'))
		self.add_option(StringOption(_('AgeExtended'),
			'text', 			# attribute-name
			self.text,			# default-value
			_('Name'),		 		# widget-label
			_('Person to calculate age')	# description
			))
		self.add_option(StringOption(_('AgeExtended'),
			'born_date', 					# attribute-name
			self.born_date,					# default-value
			_('Date of birth'),	 			# widget-label
			_('The DateTime (YYYY-MM-DD HH:MM:SS) of birth')	# description
			))
		# add default menu items
		self.add_default_menuitems()	
		self.__timeout = gobject.timeout_add(self.__update_interval * 1000, self.update)

	def __setattr__(self, name, value):
		screenlets.Screenlet.__setattr__(self, name, value)
		

	def update(self):
		gobject.idle_add(self.redraw_canvas)
		return True

	def on_draw(self, ctx):
		counts = self.get_time_ago(self.born_date)

		# scaling above 500% is very slow
		if self.scale > 5:
			self.scale = 5
		# if theme is loaded
		if self.theme:
			ctx.save()
			ctx.scale(self.scale * 1.5, self.scale)
			ctx.translate(0, 0)
			self.theme.render(ctx, 'background')
			ctx.restore()

			ctx.save()
			ctx.scale(self.scale, self.scale)
			self.draw_text(ctx, "Age of " + self.text, 10, 10, 16)
                        if counts[4]:
				self.draw_text(ctx, counts[4], 10, 80, 12)
 			else:
				self.draw_text(ctx, counts[0], 10, 50, 12)
				if counts[1]:
					self.draw_text(ctx, counts[1], 10, 70, 12)
				if counts[2]:
					self.draw_text(ctx, counts[2], 10, 90, 12)
				if counts[3]:
					self.draw_text(ctx, counts[3], 10, 110, 12)
			ctx.restore()

			ctx.save()
			ctx.scale(self.scale * 1.5, self.scale)
			ctx.translate(0, 0)
			self.theme.render(ctx, 'glass')
			ctx.restore()

	def on_draw_shape(self, ctx):
		if self.theme:
			self.on_draw(ctx)

	def draw_text(self, ctx, value, x, y, size):
		ctx.save()
		ctx.translate(x, y)
		if self.p_layout == None : 
			self.p_layout = ctx.create_layout() 
		else: 
			ctx.update_layout(self.p_layout)
		p_fdesc = pango.FontDescription()
		p_fdesc.set_family_static("Sans")
		p_fdesc.set_size(size * pango.SCALE)
		self.p_layout.set_font_description(p_fdesc)
		self.p_layout.set_width(280 * pango.SCALE)
		self.p_layout.set_alignment(pango.ALIGN_CENTER)
		self.p_layout.set_markup(value)
		ctx.set_source_rgba(1, 1, 1, 0.8)
		ctx.show_layout(self.p_layout)
		self.p_layout.set_alignment(pango.ALIGN_LEFT)
		ctx.restore()

	def get_time_ago(self, date):
		try:
			locale.setlocale(locale.LC_ALL, '')
			then = time.mktime(time.strptime(date, "%Y-%m-%d %H:%M:%S"))
			now = time.time()
			seconds = int(now - then)
                        minutes = int(seconds / 60)
                        hours = int(minutes / 60)
                        days = int(hours / 24)
                        if seconds > 0:
				seconds = _("Seconds: ") + locale.format("%.0d",seconds,1)
			else:
				return 0, 0, 0, 0, _("Future date not allowed")
			if minutes > 0:
                        	minutes = _("Minutes: ") + locale.format("%.0d",minutes,1)
			else:
				minutes = 0
			if hours > 0:
                        	hours = _("Hours: ") + locale.format("%.0d",hours,1)
			else:
				hours = 0
			if days > 0:
                        	days = _("Days: ") + locale.format("%.0d",days,1)
			else:
				days = 0
			return seconds, minutes, hours, days, 0
		except ValueError:
			return 0, 0, 0, 0, _("Invalid date format")
	
# 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(AgeExtendedScreenlet)
