#!/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 datetime
import locale
import pango
import math
import os
import Image
import time
import datetime
import Sun
#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 dayNightScreenlet(screenlets.Screenlet):
	"""Displays the Earth with its shadow"""

	# Default Meta Info for Screenlet
	__name__ = 'Day and Night'
	__version__ = '0.2'
	__author__ = 'Karim "mouton sauvage" El Khalifa'
	__desc__ = __doc__

	# Internal Variables
	__timeout = None
	p_layout = None
	

	# editable options and defaults
	update_interval = 300
	mytext = ""
	x1 = -10000
	resolution = 0
	width = 480
	height= 240	
	
# 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=480, height=240, **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
		self.add_default_menuitems()
		# Add an extra tab under the "options" tab on the "properties" dialog
		self.add_options_group(_('System'), _('Day and night Display Options'))
		self.add_option(IntOption(_('System'), 'update_interval', 
			self.update_interval, _('Update interval'), 
			_('The interval for updating info (in seconds)'), min=1, max=600))
		# Set the update interval (In this case, how often the canvas should be redrawn
		self.update_interval = self.update_interval
		
		self.makeEarth()
		

	# 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)
		# Set up a timer based on the "update_interval" value defined above
		if name == "update_interval":
			if value > 0:
				# Create a 'dictionary' with the update_interval value
				self.__dict__['update_interval'] = value
				# If the timer exists and has timed out, remove it
				if self.__timeout:
					gobject.source_remove(self.__timeout)
				# Create the timer with a value of value * 1000
				# Because the timer accepts a time value in milliseconds
				# Note that the object calls the function update() on timeout*
				self.__timeout = gobject.timeout_add(int(value * 60 * 1000), self.update)
			else:
				# If 'value' isn't set it, set it as 1 (second) in the 'dictionary'
				self.__dict__['update_interval'] = 1
				pass


	def makeEarth(self):
		
		(year, month, day, hour, minu, sec, temp, yday, gmt) = time.gmtime()
		
		# premier jour à partir de l'équinoxe
		(temp, temp, temp, temp, temp, temp, temp, fday, temp) = time.gmtime(time.mktime((year, 3, 21, 4, 0, 0, 0, 0, 0)))
		
		fLon = 0 # 0 = greenwich
		
		cSun = Sun.Sun()
		tToday = time.gmtime(time.time())
		
		# calcul du decalage de l'ombre du à l'heure
		
		#decalage = int(250 - (float(hour) + minu/60.0 + sec/3600.0) / 24 * 250) - 125
		decalage = int(480 - (float(hour) + minu/60.0 + sec/3600.0) / 24 * 480) - (480/2)
		
		
		fore = Image.open(os.path.abspath(os.path.dirname(__file__)) + "/earth/" + str(month) + ".png")
		back = Image.open(os.path.abspath(os.path.dirname(__file__)) + "/earth/night.png")
		
		for i in range(0,self.height):
		
			if i < self.height/2:
				fLat = 90-((i/(self.height/2.0)))*90
			else:
				fLat = -(((i-(self.height/2.0))/(self.height/2.0))*90)
				
			# Get the value for today
			(fTodaySunriseTime, fTodaySunsetTime) = cSun.sunRiseSet(tToday[0], tToday[1], tToday[2], fLon,fLat)
			jour = fTodaySunsetTime - fTodaySunriseTime
			
			x1 = max(0, (self.width/2) - int(self.width/24*jour/2) + decalage)
			x2 = min(self.width, ((self.width/2) + int(self.width/24*jour/2)) + decalage)
			box = (x1 ,i,x2,i+1)
	
			region = fore.crop(box)
			back.paste(region, box)
			
			########################
			x1 = min(self.width, (self.width + self.width/2) - int(self.width/24*jour/2) + decalage)
			x2 = self.width
			box = (x1 ,i,x2,i+1)
	
	
			region = fore.crop(box)
			back.paste(region, box)			
			#######################
			
			x1 = 0
			x2 = max(0,-(self.width/2) + int(self.width/24*jour/2) + decalage)
			box = (x1 ,i,x2,i+1)
				
			region = fore.crop(box)
			back.paste(region, box)			
			#######################
			
			i = i + 1
			
		back.save(os.path.abspath(os.path.dirname(__file__)) + "/im.png")
		
	# Define the update function - in this case, what to do when the timer expires
	def update(self):
		self.makeEarth()
		print "redraw"
		# Redraw the canvas
		self.redraw_canvas()
		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)
			ctx.set_source_surface(cairo.ImageSurface.create_from_png(os.path.abspath(os.path.dirname(__file__)) + "/im.png"), 0, 0)
			ctx.paint()

			ctx.restore()

	# 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)

# 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(dayNightScreenlet)
	
