#!/usr/bin/env python

# SearchTorrentScreenlet  (c) 2008 by JR
#


import screenlets
import cairo
import gtk
import wnck
import urllib2
from os import system
from screenlets import DefaultMenuItem
from screenlets.options import BoolOption
import RequestHandling


def callback(stuff, event, siteAndLink):
		if siteAndLink[0]=='Torrentz':
			system("gnome-open '" + siteAndLink[1] + "'" )
		elif siteAndLink[0]=='TPB':
			if event.button==1:
				link = siteAndLink[1]
				filename = link[link.rfind('/')+1:link.find('.torrent')+8]
				downloadfile = urllib2.urlopen(link)
				diskfile = file('/tmp/' + filename, 'w')
		        	diskfile.write(downloadfile.read())
		        	downloadfile.close()	
        			diskfile.close()
				system("gnome-open '" + '/tmp/' + filename + "'")
			else:
				system("gnome-open '" + siteAndLink[2] + "'" )
		elif siteAndLink[0]=='Mininova':
			if event.button==1: #left mouseclick
				link = siteAndLink[1]
				filename = link[link.rfind('/')+1:] + '.torrent'			
				downloadfile = urllib2.urlopen(link)
				diskfile = file('/tmp/' + filename, 'w')
			        diskfile.write(downloadfile.read())
			        downloadfile.close()	
        			diskfile.close()
				system("gnome-open '" + '/tmp/' + filename + "'")
			else:
				system("gnome-open '" + siteAndLink[2] + "'" )

class SearchTorrentScreenlet (screenlets.Screenlet):
	"""A Torrent Search Screenlet, If you use this screenlet to make other html screenlets please give me some credits"""
	
	# default meta-info for Screenlets
	__name__		= 'Torrent Search Screenlet'
	__version__		= '0.4.test'
	__author__		= 'JR build on GoogleMapScreenlet by Helder Fraga aka Whise'
	__desc__		= __doc__
	width =425
	height = 120
	result = None
	hbox = None
	box = gtk.VBox(False, 0)
	search = False
	Torrentz = True
	TPB = False
	Mininova = False
		
	

	def callback(self, widget, data):
		sites = [self.TPB,self.Mininova,self.Torrentz]
		results = RequestHandling.buildResultList(self.entry.get_text(),sites)
		table = self.buildResultsTable(results)
		self.search = True
		if self.result != None:
			self.result.hide()
			self.result.destroy()
		self.result = gtk.ScrolledWindow()
		self.result.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)			
		self.result.add_with_viewport(table)
		self.result.set_size_request(int(1*self.scale),int((470 -110)*(self.scale)-(self.scale*6)))
		self.box.pack_start(self.result, False, False, 0)
		self.height = 470*self.scale
		self.result.show_all()
		self.redraw_canvas()
		

	def on_key_down(self, keycode, keyvalue, event):
		"""Called when a keypress-event occured in Screenlet's window."""
		key = gtk.gdk.keyval_name(event.keyval)
		
		if key == "Return" or key == "Tab":
			sites = [self.TPB,self.Mininova,self.Torrentz]
			results = RequestHandling.buildResultList(self.entry.get_text(),sites)
			table = self.buildResultsTable(results)
			self.search = True
			if self.result != None:
				self.result.hide()
				self.result.destroy()
			self.result = gtk.ScrolledWindow()
			self.result.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)			
			self.result.add_with_viewport(table)
			self.result.set_size_request(int(1*self.scale),int((470 -110)*(self.scale)-(self.scale*6)))
			self.box.pack_start(self.result, False, False, 0)
			self.height = 470*self.scale
			self.result.show_all()
	
	def on_mouse_down (self, event):
		"""Called when a buttonpress-event occured in Screenlet's window. 
		Returning True causes the event to be not further propagated."""
		if event.button != 1 or event.type != gtk.gdk.BUTTON_PRESS:
			return False
		x = event.x / self.scale
		y = event.y / self.scale
		if x >=355 and x <= 420:
			if y>=445 and y<= 460:
# minimize so destroy the original searchresult window!
				self.height = 120*self.scale
				self.search = False
				self.result.hide()
				self.result.destroy()
				self.result = None
				self.redraw_canvas()
		return False

	def __init__ (self, **keyword_args):
		# init stuff
		screenlets.Screenlet.__init__(self, width=int(self.width*self.scale), height=int(self.height*self.scale),uses_theme=True, 
			is_widget=False, is_sticky=True, **keyword_args)		
		#self.add_default_menuitems(menu.xml)
		#self.add_default_menuitems(DefaultMenuItem.XML)
		self.add_options_group('Sites', 'Select the sites you want to check...')
		self.add_option(BoolOption('Sites','Torrentz', self.Torrentz, 'Torrentz', ''))
		self.add_option(BoolOption('Sites','Mininova', self.Mininova, 'Mininova', ''))
		self.add_option(BoolOption('Sites','TPB', self.TPB, 'ThePiratebay', ''))

		self.theme_name = "default"
		if self.box != None:
			self.box.set_border_width(int(15*self.scale))
			self.box.set_size_request(int(1*self.scale),int((470 -110)*(self.scale)-(self.scale*6)))
		
		# add/show all inputs
			self.hbox = gtk.HBox(False,0)
			self.button1 = gtk.Button("Search")
			self.hbox.pack_start(self.button1,False,False,0)
			self.button1.connect("clicked", self.callback, "Search")
			self.entry = gtk.Entry(256)
			self.hbox.pack_start(self.entry,True,True,0)			
			self.box.pack_start(self.hbox,False,False,0)
			self.box.set_uposition(1,46)
			self.window.add(self.box)		
			self.window.show_all()

	def __setattr__(self, name, value):
		# call Screenlet.__setattr__ in baseclass (ESSENTIAL!)
		screenlets.Screenlet.__setattr__(self, name, value)
		if name == 'Torrentz' or name=="TPB" or name=="Mininova":
			screenlets.Screenlet.__setattr__(self, name, value)
			self.redraw_canvas()

	def on_init (self):
		print "Screenlet has been initialized."
		self.add_default_menuitems(
			DefaultMenuItem.WINDOW_MENU | 
			DefaultMenuItem.PROPERTIES | 
			DefaultMenuItem.DELETE)
		self.disable_option('scale')

	def on_menuitem_select (self, id):
		"""handle MenuItem-events in right-click menu"""
		

	def on_draw (self, ctx):
		ctx.scale(self.scale, self.scale)
		ctx.set_source_rgba(0, 0, 0, 0)
 		ctx.rectangle(0, 0, self.width*self.scale, self.height*self.scale)
		ctx.fill()
		
		if self.theme and self.search:
			self.theme['bg.svg'].render_cairo(ctx)
			ctx.save()
			n = 1
			m = 10
			# draw fields
			ctx.translate(355, 445)
			ctx.scale(0.12, 0.12)
			ctx.translate(-50, m)
			self.theme['minimize.svg'].render_cairo(ctx)
			ctx.restore()
		else:
			self.theme['small.svg'].render_cairo(ctx)
			
		

	def on_draw_shape (self, ctx):
		ctx.scale(self.scale, self.scale)
		ctx.set_source_rgba(0, 0, 0, 1)
 		ctx.rectangle(0, 0, self.width*self.scale, self.height*self.scale)
		ctx.fill()
		if self.theme:
			self.theme['bg.svg'].render_cairo(ctx)
	
	

	def buildResultsTable(self, results):
		pangoMarkupCat = "<span foreground=\"orange\"><b>%s</b></span>"
		pangoMarkup = "<span foreground=\"red\"><small><b>%s</b></small></span>"
		pangoMarkupLink = "<span foreground=\"blue\"><small><b><u>%s</u></b></small></span>"
		color = gtk.gdk.Color(0,0,0,0)
		maineventbox = gtk.EventBox()
		maineventbox.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#000000"))
		table = gtk.Table(1,5, False)
		table.set_row_spacings(1)
		table.set_col_spacings(1)
		maineventbox.add(table)
		col = 0
		row = 0
		for cat, l in results.iteritems():
			#add category header to table
			label = gtk.Label()
			label.set_alignment(0,0)
			labeltxt = pangoMarkupCat % cat
			label.set_markup(labeltxt)
			table.attach(label,0,5,row,row+1)
			row = row + 1
			for sublist in results[cat]:
				table.resize(row,5)
				col = 0
				for content in sublist:
					if col == 4:
						eventbox.connect("button_press_event", callback, content)
						continue
					label = gtk.Label()
					label.set_alignment(0,0)
					if col == 0:
						eventbox = gtk.EventBox()
						eventbox.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#000000"))
						label.set_line_wrap(True)
						label.set_width_chars(32)
						labeltxt = pangoMarkupLink % content
						label.set_markup(labeltxt)
						eventbox.add(label)
						table.attach(eventbox,col, col + 1,row,row + 1)
					else:
						labeltxt = pangoMarkup % content
						label.set_markup(labeltxt)					
						table.attach(label,col, col + 1,row,row + 1)
					col = col + 1
				row = row + 1
				
		return maineventbox

if __name__ == "__main__":
	# create new session
	import screenlets.session
	screenlets.session.create_session(SearchTorrentScreenlet)

