#!/usr/bin/python
# -*- coding: utf-8 -*-

import gtk, glib
from lib import scrollframe, wrap_label, modifs

def get_str_size(size):
	unite = "o"
	if size >= 1024:
		size /= 1024.
		unite = "Ko"
		if size >= 1024:
			size /= 1024.
			unite = "Mo"
			if size >= 1024:
				size /= 1024.
				unite = "Go"
	return str(round(size, 2)) + " " + unite

class InstallDialog(gtk.Dialog):
	def __init__(self, db, apps):
		self.db = db
		
		# Initialisation de la fenetre
		gtk.Dialog.__init__(self, "Gestionnaire d'installation", None, gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT|gtk.DIALOG_NO_SEPARATOR, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_APPLY, gtk.RESPONSE_OK))
		self.set_icon_list(gtk.gdk.pixbuf_new_from_file("icons/SynApps16.png"), gtk.gdk.pixbuf_new_from_file("icons/SynApps24.png"), gtk.gdk.pixbuf_new_from_file("icons/SynApps32.png"), gtk.gdk.pixbuf_new_from_file("icons/SynApps64.png"), gtk.gdk.pixbuf_new_from_file("icons/SynApps128.png"))
		self.set_border_width(5)
		self.set_default_size(400, 300)
		self.connect("destroy", self.close)
		
		vbox = self.get_content_area()
		
		table = gtk.Table()
		table.set_border_width(5)
		table.set_row_spacings(5)
		table.set_col_spacings(5)
		vbox.pack_start(table, False, True)
		
		table.attach(gtk.image_new_from_file("icons/install.png"), 0, 1, 0, 2, gtk.FILL, gtk.FILL)
		
		self.titlelabel = gtk.Label()
		self.titlelabel.set_use_markup(True)
		self.titlelabel.set_markup("<b>Installer de nouvelles applications</b>")
		table.attach(self.titlelabel, 1, 2, 0, 1, gtk.FILL|gtk.EXPAND, gtk.FILL|gtk.EXPAND)
		
		self.desclabel = gtk.Label("Les applications suivantes vont être installées")
		table.attach(self.desclabel, 1, 2, 1, 2, gtk.FILL|gtk.EXPAND, gtk.FILL|gtk.EXPAND)
		
		frame = scrollframe.scrollframe()
		self.applist = installlist(self.db, apps)
		frame.add_with_viewport(self.applist)
		vbox.pack_start(frame, True, True)
	
	def run(self):
		self.show_all()
		response = gtk.Dialog.run(self)
		
		if response == gtk.RESPONSE_OK:
			dialog = modifs.modifs(self, self.db)
			dialog.connect("destroy", self.end_modifs)
			dialog.run()
		
		self.destroy()
		
	def end_modifs(self, widget=None):
		dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, "Les applications ont été installées avec succés.")
		dialog.run()
		dialog.destroy()
	
	def close(self, widget):
		"""Quitte gtk quand l'application est fermée."""
		gtk.main_quit()

class installlist(gtk.TreeView):
	def __init__(self, db, apps):
		self.db = db
		self.store = store(db, self, apps)

		gtk.TreeView.__init__(self, self.store)
		self.set_headers_visible(False)
		
		self.icon_cellrenderer = gtk.CellRendererPixbuf()
		
		self.name_cellrenderer = gtk.CellRendererText()
		
		self.icon_column = gtk.TreeViewColumn('')
		self.name_column = gtk.TreeViewColumn('Application', self.name_cellrenderer, markup=1)
		self.name_column.set_sort_order(gtk.SORT_ASCENDING)
		self.append_column(self.icon_column)
		self.append_column(self.name_column)
		
		self.icon_column.pack_start(self.icon_cellrenderer, True)
		self.icon_column.add_attribute(self.icon_cellrenderer, 'pixbuf', 0)

class store(gtk.ListStore):
	def __init__(self, db, parent, apps):
		self.parent = parent
		self.db = db
		gtk.ListStore.__init__(self, gtk.gdk.Pixbuf, str, int)
		
		errors = []
		
		for appname in apps:
			app = self.db.get_app(name=appname)
			if app != None:
				if app["state"] < 2:
					self.db.set_change(app["appid"], 2)
					try:
						icon = gtk.gdk.pixbuf_new_from_file(app["icon"]).scale_simple(24,24,gtk.gdk.INTERP_BILINEAR)
					except glib.GError:
						icon = self.parent.render_icon(gtk.STOCK_MISSING_IMAGE, gtk.ICON_SIZE_LARGE_TOOLBAR)
					
					version = self.db.get_downloads(app["appid"])[0]["version"]
					self.append([icon, "<big>" + app["parentname"] + "</big> <small>" + str(version) + "\n" + app["desc"] + " (" + get_str_size(app["size"]) + ")</small>", app["appid"]])
			else:
				errors.append(appname)
		
		if len(errors) > 0:
			errordialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, "Les applications suivantes ne sont pas présentes dans les dépôts: " + ", ".join(errors))
			errordialog.run()
			errordialog.destroy()
