#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable-msg=C0103
import sys
import sqlite3

try:
    from gi.repository import Gtk as gtk
except:
    print('GTK not available')
    sys.exit(1)

class TarifCig:

    def on_window1_destroy(self, object, data=None):
        #print("quitter depuis croix")
        gtk.main_quit()

    def on_gtk_quit_activate(self, menuitem, data=None):
        #print("quitter depuis menu")
        gtk.main_quit()

    def on_gtk_about_activate(self, menuitem, data=None):
        #print("about selectionne")
        self.response = self.aboutdialog.run()
        self.aboutdialog.hide()
    
    def on_gtk_search_activate(self, menuitem, data=None):
        #print("lancement de la recherche")
        self.response = self.dialogSearch.run()
        self.dialogSearch.hide()

    def on_btcancel_clicked(self, object, data=None):
        print("clic sur annuler")

    def on_btsearch_clicked(self, object, data=None):
        #print("recherche: " +  self.search.get_text())
        self.label1.set_text("Recherche : "  +  self.search.get_text())

        # On commence par vider le liststore (2è recherche)
        if len(self.table) != 0:
           self.table.clear()
        
        db = sqlite3.connect("tarifs.db")
        cursor = db.cursor()
        cursor.execute('select * from mars2013 where nom like "%{0}%"'.format( self.search.get_text()))
        db.commit()
        rs = cursor.fetchall()
        ct = 0
        for item in rs:
            ct += 1
            iter = self.table.append()
            #self.table.set(iter, 0, item[0], 1, item[1] + " €" if item[1] != '' else '', 2, item[2] + " €" if item[2] != '' else '')
            self.table.set(iter, 0, item[0], 1, item[1], 2, item[2])
            #print( item)
            #self.table.append([item[0], item[1], item[2]])
        cursor.close()

  	# On affiche le nombre de résultats trouvés par la requête
        if ct == 0:
            self.statusbar.push(self.context_id, "Aucun résultat trouvé")
        else:
            self.statusbar.push(self.context_id, str(ct) + " résultats trouvés")


    def on_treeview1_row_activated(self, widget, position, column):
        selection = self.tree.get_selection()
        (model, iter) = selection.get_selected()
        self.valeur.clear()
        self.valeur.append(model.get_value(iter, 0))
        self.valeur.append(model.get_value(iter, 1))
        self.valeur.append(model.get_value(iter, 2))

    def on_treeview1_button_press_event(self, treeview, event):
        x = int(event.x)
        y = int(event.y)
        if event.button == 3: # Clic droit
            pthinfo = self.tree.get_path_at_pos(x, y)
            if pthinfo is not None:
                path, col, cellx, celly = pthinfo
                self.tree.grab_focus()
                self.tree.set_cursor( path, col, 0)
            self.popup.show_all();
            self.popup.popup(None, None, None, None, event.button, event.time)
            

    def on_copier_activate(self, menuitem, data=None):
        
        try:
            import pyperclip
        except:
            print('pyperclip not available')
            return False 
        selection = self.tree.get_selection()
        (model, iter) = selection.get_selected()
        # On copie dans le presse papier
        pyperclip.copy(model.get_value(iter, 0) + ';' + model.get_value(iter, 1) + ';' + model.get_value(iter, 2))

    def cell_edited_callback(self, cellule, path, new_text,col, model=None):
        iter = self.table.get_iter(path)
        self.table.set_value(iter, 0, new_text)
        self.update_db(tuple(self.valeur),tuple(self.table[path]))

    def update_db(self, old_value, new_value):
        db = sqlite3.connect("tarifs.db")
        cursor = db.cursor()
        cursor.execute('update mars2013 set Nom = "{0}", Prix_Unite = "{1}", Prix_Conditionne = "{2}" where Nom = "{3}" and Prix_Unite = "{4}" and Prix_Conditionne = "{5}"'.format(new_value[0],new_value[1],new_value[2],old_value[0],old_value[1],old_value[2]))
        db.commit()
        cursor.close()

    def __init__(self):
        self.gladefile = "ui.glade"
        self.builder = gtk.Builder()
        self.builder.add_from_file(self.gladefile)
        self.builder.connect_signals(self)
        self.window = self.builder.get_object("window1")
        self.aboutdialog = self.builder.get_object("aboutdialog1")
        self.dialogSearch = self.builder.get_object("dialogSearch")
        self.label1 = self.builder.get_object("label1")
        self.search = self.builder.get_object("entry1")
        self.statusbar = self.builder.get_object("statusbar1")
        self.context_id = self.statusbar.get_context_id("exemple")
        self.actions = self.builder.get_object("actiongroup1")
        self.popup = self.builder.get_object("popup")
        self.table = self.builder.get_object("liststore1")
        self.valeur = []
        # Constuire l'entête du treeview
        self.cell = gtk.CellRendererText()
        self.cell2 = gtk.CellRendererText()
        self.cell3 = gtk.CellRendererText()
        self.cell.connect('edited', self.cell_edited_callback, 1)
        self.cell2.connect('edited', self.cell_edited_callback, 2)
        self.cell3.connect('edited', self.cell_edited_callback, 3)
        self.cell.set_property('editable', True)
        self.cell2.set_property('editable', True)
        self.cell3.set_property('editable', True)
        self.tree = self.builder.get_object("treeview1")
        self.column1 = gtk.TreeViewColumn('Nom', self.cell, text=0)
        self.column1.set_sort_column_id(0)
        self.tree.append_column(self.column1)
        self.column2 = gtk.TreeViewColumn('Prix unitaire', self.cell2, text=1)
        self.column2.set_sort_column_id(1)
        self.tree.append_column(self.column2)
        self.column3 = gtk.TreeViewColumn('Prix conditionné', self.cell3, text=2)
        self.column3.set_sort_column_id(2)
        self.tree.append_column(self.column3)
        self.window.show_all()

if __name__ == "__main__":
    main = TarifCig()
    gtk.main()
