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

import gtk, gobject
from lib import scrollframe, wrap_label, modifs, progress_dialog

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 UpdateDialog(gtk.Window):
	def __init__(self, db):
		self.db = db
		
		# Initialisation de la fenetre
		gtk.Window.__init__(self)
		self.set_title("Gestionnaire de mises à jour")
		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)
		
		table = gtk.Table()
		table.set_border_width(5)
		table.set_row_spacings(5)
		table.set_col_spacings(5)
		self.add(table)
		
		table.attach(gtk.image_new_from_file("icons/update.png"), 0, 1, 0, 2, gtk.FILL, gtk.FILL)
		
		self.titlelabel = gtk.Label()
		self.titlelabel.set_use_markup(True)
		table.attach(self.titlelabel, 1, 2, 0, 1, gtk.FILL|gtk.EXPAND, gtk.FILL)
			
		self.desclabel = wrap_label.WrapLabel("")
		self.desclabel.set_justify(gtk.JUSTIFY_CENTER)
		table.attach(self.desclabel, 1, 2, 1, 2, gtk.FILL|gtk.EXPAND, gtk.FILL)
			
		frame = scrollframe.scrollframe()
		self.applist = updatelist(self.db)
		frame.add_with_viewport(self.applist)
		table.attach(frame, 0, 2, 2, 3, gtk.FILL|gtk.EXPAND, gtk.FILL|gtk.EXPAND)
			
		bbox = gtk.HButtonBox()
		bbox.set_layout(gtk.BUTTONBOX_END)
		table.attach(bbox, 0, 2, 3, 4, gtk.FILL|gtk.EXPAND, gtk.FILL)
		
		self.cancelbutton = gtk.Button(stock=gtk.STOCK_CANCEL)
		self.cancelbutton.connect('clicked', self.cancel)
		bbox.pack_start(self.cancelbutton)
		
		self.applybutton = gtk.Button(stock=gtk.STOCK_APPLY)
		self.applybutton.connect('clicked', self.apply)
		bbox.pack_start(self.applybutton)
	
	def update(self, silent=False):
		self.applist.store.update()
		if len(self.db.get_apps(-2)) > 0:
			self.titlelabel.set_markup("<b>Des mises à jour sont disponibles</b>")
			self.desclabel.set_text("Si vous ne souhaitez pas les installer maintenant, vous pouvez les retrouver plus tard dans SynApps.")
			
			self.show_all()
		else:
			if silent:
				self.destroy()
			else:
				self.titlelabel.set_markup("<b>Aucunes mises à jour disponibles</b>")
				self.desclabel.set_text("Toutes vos applications sont déjà à jour.")
				
				self.show_all()
				self.applybutton.hide()
	
	def cancel(self, widget):
		self.destroy()
	
	def apply(self, widget):
		if len(self.db.get_apps_to_update()) > 0:
			dialog = modifs.modifs(self, self.db)
			dialog.run()
			dialog.connect('destroy', self.refresh)
		else:
			self.destroy()
	
	def refresh(self, widget=None):
		"""Actualise les listes."""
		self.refresh_finished = False
		dialog = progress_dialog.progress_dialog()
		dialog.run()
		dialog.connect("destroy", self.refresh_end)
		
		gobject.idle_add(self.thread_refresh, dialog)

	def thread_refresh(self, dialog):
		try:
			self.db.update(True)
		except IOError as message:
			errordialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, str(message))
			errordialog.run()
			errordialog.destroy()
			
		self.refresh_finished = True
		dialog.destroy()
		
		return False

	def refresh_end(self, widget):
		if self.refresh_finished:
			self.update()
		
	def close(self, widget=None):
		"""Quitte gtk quand l'application est fermée."""
		gtk.main_quit()

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

		gtk.TreeView.__init__(self, self.store)
		self.set_headers_visible(False)
		
		self.toggle_cellrenderer = gtk.CellRendererToggle()
		self.toggle_cellrenderer.set_property('activatable', True)
		
		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=2)
		self.name_column.set_sort_order(gtk.SORT_ASCENDING)
		self.toggle_column = gtk.TreeViewColumn('')
		self.append_column(self.toggle_column)
		self.append_column(self.icon_column)
		self.append_column(self.name_column)
		
		self.toggle_column.pack_start(self.toggle_cellrenderer, True)
		self.toggle_column.add_attribute(self.toggle_cellrenderer, 'active', 0)
		self.icon_column.pack_start(self.icon_cellrenderer, True)
		self.icon_column.add_attribute(self.icon_cellrenderer, 'pixbuf', 1)
		self.name_column.add_attribute(self.name_cellrenderer, 'text', 2)
		
		self.toggle_cellrenderer.connect("toggled", self.toggle)
	
	def toggle(self, widget, path):
		app = self.db.get_app(self.store[path][3])
		change = app["change"]
		
		if change == 2:
			change = 1
		else:
			change = 2
		
		self.db.set_change(app["appid"], change)
		
		self.store[path][0] = (change == 2)

class store(gtk.ListStore):
	def __init__(self, db, parent):
		self.parent = parent
		self.db = db
		gtk.ListStore.__init__(self, gobject.TYPE_BOOLEAN, gtk.gdk.Pixbuf, str, int)
	
	def update(self):
		self.clear()
		for app in self.db.get_apps(-2):
			self.db.set_change(app["appid"], 2)
		
		for app in self.db.get_apps(-2):
			try:
				icon = gtk.gdk.pixbuf_new_from_file(app["icon"]).scale_simple(24,24,gtk.gdk.INTERP_BILINEAR)
			except:
				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([(app["change"] == 2), icon, "<big>" + app["parentname"] + "</big> <small>" + str(version) + "\n" + app["desc"] + " (" + get_str_size(app["size"]) + ")</small>", app["appid"]])
