import gtk
import gobject
import os
import adesk.core as Core
import adesk.barconf as BarConf

# position in list
ID_ICON  = 0
ID_NAME = 1
ID_CMD = 2
ID_IMG = 3

class config(gtk.Frame):
    def __init__(self, conf, ind):
        gtk.Frame.__init__(self)
        self.conf = conf
        self.ind = ind

        self.set_border_width(5)
        framebox = gtk.VBox(False, 0)
        framebox.set_border_width(5)
        framebox.set_spacing(10)
        self.add(framebox)

        BoxListControls = gtk.VBox(False,0)

        # ListStore
        self.view = View()

        if self.conf.drawer.has_key(ind):
            self.view.add_list(self.conf.drawer[ind])

        self.view.connect("row-activated", self.edit_item)

        scrolled = gtk.ScrolledWindow()
        scrolled.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        scrolled.add(self.view)

        frame = gtk.Frame()
        frame.add(scrolled)

        ## Control buttons for list
        # Add Launcher
        button = Core.image_button('add custom launcher', 'images/conf/add_custom.png', 24)
        button.connect("clicked", self.new_item_custom)
        BoxListControls.pack_start(button, False, False)

        #~ # Add from menu
        button = Core.image_button('add from menu', 'images/conf/add_app.png', 24)
        button.connect("clicked", self.new_item_menu)
        BoxListControls.pack_start(button, False, False)

        # Remove
        button = Core.image_button('remove', 'images/conf/remove.png', 24)
        button.connect("clicked", self.remove_item)
        BoxListControls.pack_start(button, False, False)

        box = gtk.HBox()
        box.pack_start(BoxListControls, False, False)
        box.pack_start(frame, True)

        framebox.pack_start(box, True)

    def remove_item(self, widget):
        self.view.remove_item()

    def edit_item(self, view, path=None, view_column=None):
        selection = view.get_cursor()[0][0]
        if (selection is not None):
            model   = view.get_model()
            BarConf.Edit_Item(self.conf.window, self, model, selection, True)

    def new_item_custom(self, widget):
        self.view.new_entry()
        self.edit_item(self.view)

    def new_item_menu(self, widget):
        self.view.new_entry()
        selection = self.view.get_cursor()[0][0]
        if (selection is not None):
            model   = self.view.get_model()
            self.conf.select_from_menu.run(model, selection, True)

    def save_change(self):
        self.conf.drawer[self.ind] = []
        model = self.view.get_model()
        iter = model.get_iter_root()

        while (iter):
            self.conf.drawer[self.ind].append((
                model.get_value(iter, ID_CMD),
                model.get_value(iter, ID_IMG),
                model.get_value(iter, ID_NAME)))
            iter = model.iter_next(iter)

class View(gtk.TreeView):

    def __init__(self):
        gtk.TreeView.__init__(self)
        self.set_headers_visible(False)
        self.set_reorderable(True)
        self.get_selection().set_mode(gtk.SELECTION_SINGLE)

        self.model = gtk.ListStore(
            gtk.gdk.Pixbuf,         # icon pixbuf
            gobject.TYPE_STRING,    # name
            gobject.TYPE_STRING,    # cmd
            gobject.TYPE_STRING,    # icon path
            )

        self.filtremodele = self.model.filter_new()
        self.set_model(self.model)

        cell = gtk.CellRendererPixbuf()
        col = gtk.TreeViewColumn(None, cell, pixbuf=ID_ICON)
        self.append_column(col)

        cell = gtk.CellRendererText()
        col = gtk.TreeViewColumn(None, cell, text=ID_NAME)
        self.append_column(col)

        cell = gtk.CellRendererText()
        col = gtk.TreeViewColumn(None, cell, text=ID_CMD)
        col.set_visible(False)
        self.append_column(col)

        cell = gtk.CellRendererText()
        col = gtk.TreeViewColumn(None, cell, text=ID_IMG)
        col.set_visible(False)
        self.append_column(col)

    def remove_item(self):
        # remove item from configuration
        try:
            #self.view.grab_focus()
            pos = self.get_cursor()[0][0]
            if pos == None: # no selection
                return

            model = self.get_model()
            #~ self.view.set_cursor(pos-1)
            #~ self.view.grab_focus()
            model.remove(model.get_iter(pos))

            if pos < 0:
                pos = 0
            # Set the focus and cursor correctly
            self.set_cursor(pos);
            self.grab_focus()
        except TypeError:
            print( "> nothing to delete !?" )

    def add_list(self, list):
        model = self.get_model()
        for my_item in list:
            item = model.append(None)
            cmd , icon_path , name = my_item
            Core.set_icon(icon_path, model, item, 32)
            model.set_value(item, ID_NAME, str(name))
            model.set_value(item, ID_CMD, str(cmd))
            model.set_value(item, ID_IMG, str(icon_path))

    # Add new treeview object, position=-1 inserts  into cursor's position
    def new_entry(self, position=-1, insertAfter=True):
        self.grab_focus()
        model = self.get_model()
        try:
            position = self.get_cursor()[0][0]
            try:
                iter = model.get_iter(position)
            except ValueError:
                print("> Empty list ?")
                iter = model.get_iter()

            if (insertAfter == True):
                item = model.insert_after(iter)
            else:
                item = model.insert_before(iter)
        except TypeError:
            print "typeError _ treeview"
            item = model.append(None)
            self.grab_focus()

        icon_path = ''
        icon = ''
        model.set_value(item, ID_NAME, '')
        model.set_value(item, ID_CMD, '')
        model.set_value(item, ID_IMG, icon_path)
        model.set_value(item, ID_ICON, Core.pixbuf_from_file(icon,32,32))
        ## Set focus to new entry and edit
        path = model.get_path(model.get_iter(position+1))
        self.set_cursor(path)

    def new_item_custom(self, widget):
        self.view.new_entry()
        self.edit_item(self.view)

    def new_item_menu(self, widget):
        self.view.new_entry()
        selection = self.view.get_cursor()[0][0]
        if (selection is not None):
            model   = self.view.get_model()
            self.conf.select_from_menu.run(model, selection)

    def edit_item(self, view, path=None, view_column=None):
        selection = view.get_cursor()[0][0]
        if (selection is not None):
            model   = view.get_model()
            Edit_Item(self.window, self, model, selection)
