#!/usr/bin/env python

#  LinuxSerbiaStats (c) Nemanja Jovicic 2008 <nemanja.jovicic@hotmail.com>
#
#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 screenlets
#from screenlets.options import StringOption, IntOption, ColorOption, BoolOption
#import cairo
#import gtk
import pango
from os import system
import gobject
from urllib import urlopen

class LinuxSerbiaStatsScreenlet(screenlets.Screenlet):
        """Display statistic of linux users of Serbia"""
	p_layout = None
	# default meta-info for Screenlets
	__name__ = 'LinuxSerbiaStats'
	__version__ = '0.2.2'
	__author__ = 'Nemanja Jovicic'
	__desc__ =__doc__

	# internals
	__timeout = None

	# editable options and defaults
	__update_interval = 900 # every 900 second-15min
	show=1
	all_data=[]
	refresh= True

	# constructor
	def __init__(self, **keyword_args):
		# call super
		screenlets.Screenlet.__init__(self, width=380, height=375, **keyword_args)
		self.x=250
		self.y=200
		# set theme
		self.theme_name = "default"

		self.add_menuitem("register", "Registruj se...")
		self.add_menuitem("reload", "Reload podataka")
		self.add_menuitem("show_1", "Prikazi sve gradove")
		self.add_menuitem("show_5", "Prikazi gradove sa 5+ korisnika")
		self.add_menuitem("show_20", "Prikazi gradove sa 20+ korisnika")
		self.add_menuitem("show_50", "Prikazi gradove sa 50+ korisnika")
		self.add_menuitem("show_100", "Prikazi gradove sa 100+ korisnika")
		self.add_menuitem("show_300", "Prikazi gradove sa 300+ korisnika")
		self.add_menuitem("home", "HomePage http://linux.dootzky.com")
		
		# add default menu items
		self.add_default_menuitems()
		
		
		self.__timeout = gobject.timeout_add(self.__update_interval * 1000, self.update)
		self.__timeout = gobject.timeout_add(self.__update_interval * 1000, self.parseDootzkyData)
		
	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):
		if self.theme:
			ctx.save()
			ctx.scale(self.scale , self.scale)
			ctx.translate(0, 0)
			self.theme.render(ctx, 'background')
			ctx.restore()
			
			#block loading from site
			if self.refresh==True:
				self.parseDootzkyData()
				self.refresh=False

			#top distros			
			self.draw_text(ctx,"Top distros:",7*self.scale,135*self.scale,"Sans Bold Italic "+str(13*self.scale),1,1,1,1)
			self.draw_text(ctx,self.all_data[2][0]['name']+": "+self.all_data[2][0]['value'],37*self.scale,153*self.scale,"Sans Bold "+str(10*self.scale),1,1,1,1)
			self.draw_text(ctx,self.all_data[2][1]['name']+": "+self.all_data[2][1]['value'],37*self.scale,166*self.scale,"Sans Bold "+str(10*self.scale),1,1,1,1)
			self.draw_text(ctx,self.all_data[2][2]['name']+": "+self.all_data[2][2]['value'],37*self.scale,179*self.scale,"Sans Bold "+str(10*self.scale),1,1,1,1)
			
			#top cities			
			self.draw_text(ctx,"Top gradovi:",7*self.scale,195*self.scale,"Sans Bold Italic "+str(13*self.scale),1,1,1,1)
			self.draw_text(ctx,self.all_data[3][0]['name']+": "+self.all_data[3][0]['value'],37*self.scale,213*self.scale,"Sans Bold "+str(10*self.scale),1,1,1,1)
			self.draw_text(ctx,self.all_data[3][1]['name']+": "+self.all_data[3][1]['value'],37*self.scale,226*self.scale,"Sans Bold "+str(10*self.scale),1,1,1,1)
			self.draw_text(ctx,self.all_data[3][2]['name']+": "+self.all_data[3][2]['value'],37*self.scale,239*self.scale,"Sans Bold "+str(10*self.scale),1,1,1,1)

			#total users			
			self.draw_text(ctx,self.all_data[1],40*self.scale,255*self.scale,"Sans Bold "+str(35*self.scale),1,1,1,1)
			self.draw_text(ctx,"~Ukupan broj linux korisnika~",3*self.scale,305*self.scale,"Monospace Bold "+str(8*self.scale),1,1,1,1)

			#drawing circles
			for x in range(int(self.all_data[0])):
				krug_size=-1

				if int(self.all_data[4][x]['users'])>300:
					krug_size=40
				elif int(self.all_data[4][x]['users'])>100:
					if self.show != 300:					
						krug_size=35
				elif int(self.all_data[4][x]['users'])>50:
					if self.show != 300 and self.show != 100:
						krug_size=27
				elif int(self.all_data[4][x]['users'])>20:
					if self.show != 300 and self.show != 100 and self.show != 50:
						krug_size=21
				elif int(self.all_data[4][x]['users'])>5:
					if self.show == 1 or self.show== 5:
						krug_size=15
				elif int(self.all_data[4][x]['users'])>0:
					if self.show == 1:
						krug_size=10
				
				if krug_size>0:
					ctx.save()
					ctx.scale(self.scale , self.scale)
					ctx.translate(105-krug_size/2+float(self.all_data[4][x]['x'])/2.172, 3-krug_size/2+float(self.all_data[4][x]['y'])/2.161)
					self.theme.render(ctx, str(krug_size))
					ctx.restore()
			
	def on_draw_shape(self, ctx):
		if self.theme:
			self.on_draw(ctx)
	
	def menuitem_callback(self, widget, id):
		screenlets.Screenlet.menuitem_callback(self, widget, id)
		if id == "show_300":
			self.show = 300
			self.update()
		if id == "show_100":
			self.show = 100
			self.update()
		if id == "show_50":
			self.show = 50
			self.update()
		if id == "show_20":
			self.show = 20
			self.update()
		if id == "show_5":
			self.show = 5
			self.update()
		if id == "show_1":
			self.show = 1		
			self.update()
		if id == "reload":
			self.parseDootzkyData()
		if id == "register":
			system("firefox http://linux.dootzky.com/register.php")
		if id == "home":
			system("firefox http://linux.dootzky.com")

			
	def draw_text(self, ctx, value, x, y, font, r,g,b,a):
		ctx.save()
		ctx.translate(x, y)
		if self.p_layout == None :                # fixed memory leak
                      self.p_layout = ctx.create_layout() 
                else: 
                      ctx.update_layout(self.p_layout) 
		p_fdesc = pango.FontDescription(font)
		self.p_layout.set_font_description(p_fdesc)
		self.p_layout.set_width(int(220 * self.scale*pango.SCALE))
		self.p_layout.set_alignment(pango.ALIGN_LEFT)
		self.p_layout.set_markup(value)
		ctx.set_source_rgba(r,g,b,a)
		ctx.show_layout(self.p_layout)
		self.p_layout.set_alignment(pango.ALIGN_LEFT)
		ctx.restore()
	
	def parseDootzkyData(self):

		self.all_data=[]
		data = urlopen('http://linux.dootzky.com/screenlet.php').read()

		cityNo=self.getBetween(data, '<cityNo>', '</cityNo>')

		userNo=self.getBetween(data, '<userNo>', '</userNo>')
		
		top_distro_data=self.getBetween(data, '<top_distro>', '</top_distro>')
		top_distros=self.parseTops(top_distro_data)		

		top_city_data=self.getBetween(data, '<top_city>', '</top_city>')
		top_cities=self.parseTops(top_city_data)
				
		all_city_data=self.getBetween(data, '<city>', '</city>')
		all_cities=self.parseCities(all_city_data,cityNo)
		
		self.all_data.append(cityNo)
		self.all_data.append(userNo)
		self.all_data.append(top_distros)
		self.all_data.append(top_cities)
		self.all_data.append(all_cities)
		
		self.update()
	

	def parseCities(self,data,cityNo):
		serb_cities=[]
		for x in range(int(cityNo)):
			dcstart = data.find('<'+str(x)+'>')
			dcstop = data.find('</'+str(x)+'>',dcstart)   
			city = data[dcstart:dcstop]		
			serb_cities.append(self.parseCity(city))
		#print serb_cities
		return serb_cities

	def parseCity(self,data):
		grad={
		'x':self.getBetween(data, '<x>', '</x>'),
		'y':self.getBetween(data, '<y>', '</y>'),
		'users':self.getBetween(data, '<users>','</users>'),
		}
		return grad

	def parseTops(self,data):
		tops=[]
		for x in range(3):
			dcstart = data.find('<No'+str(x+1)+'>')
			dcstop = data.find('</No'+str(x+1)+'>',dcstart)   
			top_data = data[dcstart:dcstop]		
			tops.append(self.parseTop(top_data))
		return tops

	def parseTop(self,data):
		top={
		'name':self.getBetween(data, '<name>', '</name>'),
		'value':self.getBetween(data, '<value>', '</value>'),
		}
		return top

	#taken from ClearWeatherScreenlet :)
	def getBetween(self, data, first, last):
		x = len(first)
		begin = data.find(first) +x
		end = data.find(last, begin)
		return data[begin:end]
	#--------------------------------------------------

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