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

#  TuxScreenlet (c) Carlos Barreto 2010 <carlobar@gmail.com>
#  Modified by Guido Tabbernuk <boamaod@gmail.com>
#
#

import screenlets
from screenlets import Screenlet

import pygtk
pygtk.require('2.0')
import gtk
import math
import cairo
import pango
import datetime
import gobject
import sys
import os
from os import environ

try:
	from Xlib import X, display 
	from Xlib.protocol import request

	display = display.Display()
	screen=display.screen()
	root=screen.root
	window=root
	
except Exception: print 'Problems initializing Xlib, nothing will work corretly'

try:
	import Image
except Exception: print 'Image library import failed'

# use gettext for translation
import gettext

_ = screenlets.utils.get_translator(__file__)

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

@tdoc
class TuxScreenlet (Screenlet):
	"""A screenlet inspired in Geyes"""
	
	# default meta-info for Screenlets
	__name__	= 'TuxScreenlet'
	__version__	= '0.1.4'
	__requires__ = [ 'python-imaging', 'python-xlib' ]
	__author__	= 'Carlos Barreto'
	__desc__	= __doc__
	
	# internal vars

	# hacky way to get screenlets own path
	cut_path_here = __file__.rfind('/')
	if cut_path_here > 0:
		screenlet_dir = __file__[0:cut_path_here]
	else:
		screenlet_dir = os.getcwd()
	
	# editable options
	# editable options (options that are editable through the UI)

	theme_ = "Tux"

	color=(0.0, 0.0, 0.0, 1)
	font= "Sans Medium 5"
	
	_x_ojo_i = 157
	_y_ojo_i = 98

	_offsetx_ojo_d = 61
	_offsety_ojo_d = 0

	_width = 400
	_height = 468


	offsetx_ojo_d = _offsetx_ojo_d
	offsety_ojo_d = _offsety_ojo_d

	x_ojo_i = _x_ojo_i
	y_ojo_i = _y_ojo_i

	posx_i = 1
	posy_i = 1
	posy_min_i = 1
	posy_max_i = 1
	incremento = 1
	color = (255, 255, 255, 255)
	referencia = 0
	scale_ = 1
	escala_anterior = 1
	_offset = 30
	offset = _offset


	ojo_i=Image.open(screenlet_dir + "/themes/"+str(theme_)+"/_ojo_i.png")

	ojo_i_ = ojo_i


	# constructor
	def __init__ (self, parent_window=None,**keyword_args):
	
		"""Create a new TuxScreenlet instance."""
		# call super (we define to use our own service here)
		Screenlet.__init__(self, uses_theme=True, width=self._width, height=self._height, **keyword_args)
		self.add_default_menuitems()
		self.scale=.5
		# set default theme for this Screenlet (causes redraw)
		# TODO: check, if theme is valid??
		
		self.theme_name = self.theme_
		self.update()
		self.__timeout = gobject.timeout_add(50, self.update)
		# create/add OptionGroups
			# add option group

		self.redraw_canvas()
	
	def on_load_theme (self): 
		"""A Callback to do special actions when the theme gets reloaded.
		(called AFTER loading theme and BEFORE redrawing shape/canvas)"""
		
		self.init_buffers()

	def on_scale (self):
		"""Called when the scale-attribute changes."""

		self.x_ojo_i = int(self._x_ojo_i*self.scale)
		self.y_ojo_i = int(self._y_ojo_i*self.scale)
		self.offsetx_ojo_d = int(self._offsetx_ojo_d*self.scale)
		self.offsety_ojo_d = int(self._offsety_ojo_d*self.scale)
		self.posy_min_i=1
		self.ojo_i=self.ojo_i_.resize((int(self.width*self.scale), int(self.height*self.scale)))
		self.offset = int(self._offset*self.scale)


		pass

	def get_pointer(self):
		if self.has_started:
			info = request.QueryPointer(display = display.display, window = root)
			self.mouse__x=float(info._data['root_x'])-self.x - self.offset
			self.mouse__y=float(info._data['root_y'])-self.y
			self.referencia = self.mouse__x


	def init_buffers (self):
		"""(Re-)Create back-/foreground buffers"""
		self.__buffer_back = gtk.gdk.Pixmap(self.window.window, 
			int(self.width * self.scale), int(self.height * self.scale), -1)
		self.__buffer_fore = gtk.gdk.Pixmap(self.window.window, 
			int(self.width * self.scale), int(self.height * self.scale), -1)
		
		pass


	
	def set_update_interval (self, interval):
		"""Set the update-time in milliseconds."""
		if self.__timeout:
			gobject.source_remove(self.__timeout)
		self.__timeout = gobject.timeout_add(interval, self.update)




	def update (self):
		"""Update the time and redraw the canvas"""
	
		if self.has_started:

			info = request.QueryPointer(display = display.display, window = root)
			if self.referencia != float(info._data['root_x'])-self.x:
				self.redraw_canvas()
				
		return True # keep running this event

	
		

	def on_draw (self, ctx):
		# if theme is loaded
		
		if self.theme and self.has_started:

			########### OBTENER LA POSICION DEL CURSOR
			self.get_pointer()

			########### POSICION DEL OJO IZQUIERDO
			self.posx_i = self.x_ojo_i
			self.posy_i = self.y_ojo_i

			########### FONDO IMAGEN Y FONDO OJOS
			ctx.set_operator(cairo.OPERATOR_OVER)
			ctx.scale(self.scale, self.scale)
			self.theme.render(ctx,'fondo')

			ctx.save()


			posx_ojo_i=1
			posy_ojo_i=1
#################################################

			############       tomar posicion del cursor
			mouse_x=self.mouse__x	
			mouse_y=self.mouse__y
			self.color=(255, 255, 255, 255)
			a=1
			b=1

##############calcular constantes de y min y maximo
			if self.posy_min_i == 1:
				self.color = (255, 255, 255, 255)
				posx_test = self.x_ojo_i
				self.posy_min_i = self.y_ojo_i
				while self.color == (255, 255, 255, 255):
					self.posy_min_i -= 1
					self.color=self.ojo_i.getpixel((posx_test,self.posy_min_i))
				self.posy_max_i = self.y_ojo_i
				self.color = (255, 255, 255, 255)
				while self.color == (255, 255, 255, 255):
					self.posy_max_i += 1
					self.color=self.ojo_i.getpixel((posx_test,self.posy_max_i))

			###########################    ACCION CUANDO EL CURSOR SE ENCUENTRA DENTRO D ELA IMAGEN
			
			if ((mouse_x < int(self.width*self.scale) and mouse_x > 0)) and ((mouse_y < int(self.height*self.scale)) and (mouse_y > 0)):
				on='verdadero'
				self.color=self.ojo_i.getpixel((mouse_x,mouse_y))
				if self.color == (255, 255, 255 , 255) :
					self.posx_i = mouse_x 
					self.posy_i = mouse_y 
				else:
					self.color = (255, 255, 255, 255)
				
				#####################excepcion cuando se esta en la coordenada x del ojo
					if mouse_x == self.x_ojo_i:
						self.posx_i = self.x_ojo_i
						if mouse_y < self.y_ojo_i:
							self.posy_i=self.posy_min_i
						else:# mouse_y > self.y_ojo_i:
							self.posy_i=self.posy_max_i
				########################encontrar la ecuacion de la recta
					else:
						b=(mouse_y-self.y_ojo_i)/(mouse_x-self.x_ojo_i)
						a=self.y_ojo_i - b * self.x_ojo_i
						if mouse_x > self.x_ojo_i :
							self.incremento = 1
						else:
							self.incremento = -1

						self.posx_i= self.x_ojo_i   ##############modificado
						while self.color == (255, 255, 255, 255):
							self.color = (0,0,0,0)
							self.posx_i += 1 * self.incremento
							posx_ojo_i=(self.posx_i)
							self.posy_i = a + b * (self.posx_i)
							posy_ojo_i=int(self.posy_i) 

							self.color=self.ojo_i.getpixel((posx_ojo_i,posy_ojo_i))			
						if self.posy_i < self.posy_min_i:
							self.posy_i=self.posy_min_i
						elif self.posy_i > self.posy_max_i:
							self.posy_i=self.posy_max_i		
			else:		
				on = 'falso'
				if mouse_x == self.x_ojo_i:
					self.posx_i = self.x_ojo_i
					if mouse_y < self.y_ojo_i:
						self.posy_i=self.posy_min_i
					else:
						self.posy_i=self.posy_max_i
				else:
				#############ojo izquierdo				
					b=(mouse_y-self.y_ojo_i)/(mouse_x-self.x_ojo_i)
					a=self.y_ojo_i - b * self.x_ojo_i
					if mouse_x > self.x_ojo_i :
						self.incremento = 1
					else:
						self.incremento = -1

					self.posx_i= self.x_ojo_i
					while self.color == (255, 255, 255, 255):
						self.color = (0,0,0,0)
						self.posx_i += 1 * self.incremento
						posx_ojo_i=(self.posx_i)
						self.posy_i = a + b * (self.posx_i)
						posy_ojo_i=int(self.posy_i) 
						try:

							self.color=self.ojo_i.getpixel((posx_ojo_i, posy_ojo_i))			
						except:
							self.color=(0,0,0,0)


					if self.posy_i < self.posy_min_i:
						self.posy_i=self.posy_min_i
					elif self.posy_i > self.posy_max_i:
						self.posy_i=self.posy_max_i



			ctx.translate (0, 0 )

			ctx.translate( int(((self.posx_i) - ((self.width*self.scale) / 2)) / self.scale), int(((self.posy_i) - ((self.height*self.scale) / 2)) / self.scale ))

			self.theme.render(ctx,'ojo_i')
			ctx.restore()
			ctx.save()
			
#######################################ojo derecho

			ctx.translate (0, 0 )
			ctx.translate( int((self.posx_i - (self.width*self.scale / 2)) / self.scale + self._offsetx_ojo_d) , int((self.posy_i - (self.height*self.scale / 2)) / self.scale  + self._offsety_ojo_d ))

			self.theme.render(ctx,'ojo_d')
			ctx.restore()
			ctx.save()

	

			ctx.translate (0, 0 )		
			self.theme.render(ctx,'cara')


	def on_draw_shape (self, ctx):
		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
if __name__ == "__main__":
	# create new session
	import screenlets.session
	screenlets.session.create_session(TuxScreenlet)
