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

import gtk, gobject, pango

class cattree(gtk.TreeView):
	
	__gsignals__ = {
		"select-cat": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (int, )),
	}

	def __init__(self, db):
		self.db = db
		
		self.store = store(db)
		
		gtk.TreeView.__init__(self, self.store)
		self.set_headers_visible(False)
		
		self.icon_column = gtk.TreeViewColumn('')
		self.append_column(self.icon_column)
		
		self.name_column = gtk.TreeViewColumn('Catégorie')
		self.name_column.set_sort_order(gtk.SORT_ASCENDING)
		self.append_column(self.name_column)
		
		self.icon_cellrenderer = gtk.CellRendererPixbuf()
		self.name_cellrenderer = gtk.CellRendererText()
		self.name_cellrenderer.set_property('ellipsize', pango.ELLIPSIZE_END)
		
		self.icon_column.pack_start(self.icon_cellrenderer, True)
		self.name_column.pack_start(self.name_cellrenderer, True)
		self.icon_column.add_attribute(self.icon_cellrenderer, 'pixbuf', 0)
		self.name_column.add_attribute(self.name_cellrenderer, 'text', 1)
		
		self.connect("cursor-changed", self.change)
	
	def change(self, widget):
		(store, iter) = self.get_selection().get_selected()
		self.emit("select-cat", store.get_value(iter, 2))
	
	def select(self, path):
		self.get_selection().select_path((0,))
		self.emit("select-cat", self.store[path][2])
	
	def refresh(self):
		self.store.clear()
		self.store.display_cats()
		self.select((0,))

class store(gtk.TreeStore):
	def __init__(self, db):
		self.db = db
		gtk.TreeStore.__init__(self, gtk.gdk.Pixbuf, str, int)
		
		self.display_cats()
	
	def display_cats(self, id=None, parent=None):
		for cat in self.db.get_cats(id):
			try:
				icon = gtk.gdk.pixbuf_new_from_file(cat["icon"]).scale_simple(24,24,gtk.gdk.INTERP_BILINEAR)
			except:
				icon = gtk.gdk.pixbuf_new_from_file("icons/default-cat.png").scale_simple(24,24,gtk.gdk.INTERP_BILINEAR)
			
			iter = self.append(parent, [icon, cat["name"], cat["catid"]])
			self.display_cats(cat["catid"], iter)
