#!/usr/bin/env python
# -*- coding: UTF-8 -*-

#
#Sample Screenlet
#Copyright (C) 2007 Michael W. Koehler
#
#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 2
#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, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#

# Import a few necessary components for the script to run
import screenlets
from screenlets.options import StringOption, BoolOption, IntOption
import cairo
import pango
import gtk
import gobject
import locale
import pango
import time
import os.path

#use gettext for translation
import gettext

_ = screenlets.utils.get_translator(__file__)

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

@tdoc

# Begin Creating the actual program by creating the class...MUST ACCEPT screenlets.Screenlet.
class humanPopulationScreenlet(screenlets.Screenlet):
	"""Gives an estimate of the global population at a time"""

	# Default Meta Info for Screenlet
	__name__ = 'humanPopulationScreenlet'
	__version__ = '0.1.1'
	__author__ = 'Karim El Khalifa'
	__desc__ = __doc__

	# Internal Variables
	__timeout = None
	p_layout = None

	# editable options and defaults
	base_population = 6455658790
	
	

# Define the initialization function - Some variation on this __init__ function is necessary for all screenlets.
	def __init__(self, **keyword_args):
		# Call screenlets.Screenlet.__init__ => Required!
		# Declare the basic attributes of the screenlet - width, height
		screenlets.Screenlet.__init__(self, width=250, height=100, **keyword_args)
		# Tells the screenlet which theme to use
		self.theme_name="default"
		# Create the "basic" pop-up menu that should be displayed when right-clicked
		# Add an extra tab under the "options" tab on the "properties" dialog
#		self.add_options_group('System', 'Text Display Options')

	def on_init(self):
		self.add_default_menuitems()
		if self.__timeout:
			gobject.source_remove(self.__timeout)
		self.__timeout = gobject.timeout_add(int(1000), self.update)

	# Define the __setattr__ function - This is also called when the script is executed
	def __setattr__(self, name, value):
		# Call screenlets.Screenlet.__setattr__ => Required!
		screenlets.Screenlet.__setattr__(self, name, value)

	# Define the update function - in this case, what to do when the timer expires
	def update(self):

		self.redraw_canvas()
		if self.__timeout:
			gobject.source_remove(self.__timeout)
		self.__timeout = gobject.timeout_add(int(1000), self.update)
		return True

	# The 'on_draw' function tells the script how to draw the widget
	def on_draw(self, ctx):
		# Make sure the scale value is within the acceptable range
		if self.scale > 5:
			self.scale = 5
		# If the theme is set (in our case, it is set as "default"), draw the screenlet
		if self.theme:
			# Draw background.png onto the screen (in the folder ./themes/default/)
			ctx.save()
			ctx.scale(self.scale, self.scale)
			ctx.translate(0, 0)
			self.theme.render(ctx, 'background')
			ctx.restore()

			# Draw the text onto the background
			# Depends on the 'draw_text()' function defined below
			ctx.save()
			ctx.scale(self.scale, self.scale)


			self.draw_text(ctx, _("Humans on Earth"), 70, 60, 160, "Sans", 8,1,0,0,0.8,2)
			self.draw_text(ctx, self.presentationDuNombre(self.getPopulation()), 40, 30, 130, "Sans", 20)
			ctx.restore()
			
			ctx.set_source_surface(cairo.ImageSurface.create_from_png(os.path.abspath(os.path.dirname(__file__))+"/themes/default/bonhomme.png"), 11, 30)
			ctx.paint()
			#self.theme.render(ctx, 'bonhomme')

	# This on_draw_shape provides for the majority of the functionality of the program
	# Without this function, you would be unable to "right click" on the widget (the menu
	# for the window behind it would appear) and you would be unable to move the screenlet
	# once it appears on the screen.
	def on_draw_shape(self, ctx):
		if self.theme:
			self.on_draw(ctx)

	# This is a user defined function that will tell python how to draw the text onto the background
	def draw_text(self, ctx, value, x, y, width, font, size,r=1,g=1,b=1,o=0.8,sens=1):
		ctx.save()
		ctx.translate(x, y)
		# Create a layout for the text which will be drawn on the background later
		if self.p_layout == None:
			self.p_layout = ctx.create_layout()
		else:
			ctx.update_layout(self.p_layout)
		# The next four lines set up the font for the layout
		p_fdesc = pango.FontDescription()
		p_fdesc.set_family_static(font)
		p_fdesc.set_size(size * pango.SCALE)
		self.p_layout.set_font_description(p_fdesc)
		# Define how wide the text can be that is written to the screen, in pixels
		# I want a 10 pixel border on both sides, so we will set this as 150 - 2*10 = 130px
		self.p_layout.set_width(width * pango.SCALE)
		# Left-Align the text
		if sens== 1:
			self.p_layout.set_alignment(pango.ALIGN_LEFT)
		else:
			self.p_layout.set_alignment(pango.ALIGN_RIGHT)
		self.p_layout.set_markup(value)
		# Set the color of the text
		# Setup: (RED, GREEN, BLUE, OPACITY) => All values go from 0 to 1 (float format)
		ctx.set_source_rgba(r, g, b, o)
		# Display the text
		ctx.show_layout(self.p_layout)
		# Center the text on the background
		self.p_layout.set_alignment(pango.ALIGN_CENTER)
		ctx.restore()


	def getTimeFrom2005(self):
		timeTuple=(2005,7,1, 0, 0, 0, 0, 0, 0)
		return int(time.time() - time.mktime(timeTuple))
	
	def getPopulation(self):
		return int(self.getTimeFrom2005()*2.37) + self.base_population

	def presentationDuNombre(self,num):
		strin = str(num)
		strout = ""
		mod = len(strin) % 3
		i = 1
		while i < len(strin):
			strout = strout + strin[i-1:i]
			if i % 3 == mod:
				strout = strout + "'"
			i = i+1
		strout = strout + strin[i-1:i]
		return strout
		
# If the program is run directly or passed as an argument to the python
# interpreter then create a Screenlet instance and show it
# Essentially, initialize the program
if __name__ == "__main__":
	import screenlets.session
	screenlets.session.create_session(humanPopulationScreenlet)
	
