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

import ConfigParser
import os
import sys
import pygtk
if not sys.platform == 'win32':
	pygtk.require('2.0')
import gtk
import gobject
import webbrowser
import xml.etree.ElementTree
from lib import apropos
from lib import config
from lib import confirm
from lib import descappbox
from lib import liststoreafficher
from lib import liststoreapps
from lib import modifs
from lib import preferences
from lib import treestorecat

class SynAppsMain():
	"""Classe principale de SynApps"""
	def __init__(self, mconfig):
		"""Crée la fenêtre"""
		self.filtre = ""
		self.config = mconfig
		self.modifs = modifs.modifs(self.config)
		#Configure l'affichage des icônes dans les boutons
		gtksettings = gtk.settings_get_default()
		gtksettings.set_long_property('gtk-button-images', 1, '')		
		#Creation de la fenetre
		self.fenetre = gtk.Window()
		self.fenetre.set_title("SynApps")
		self.fenetre.set_icon(gtk.gdk.pixbuf_new_from_file("img/synapps/SynApps.ico"))
		self.fenetre.set_default_size(700, 500)
		self.fenetre.connect("destroy", self.on_fenetre_destroy)
		self.fenetre.set_border_width(5)
		
		#Création de la zone du haut
		self.LabelRechercher = gtk.Label("Rechercher : ")
		self.Rechercher = gtk.Entry()
		
		self.BoutonRechercher = gtk.Button()
		self.BoutonRechercher.set_image(gtk.image_new_from_stock(gtk.STOCK_FIND, gtk.ICON_SIZE_MENU))
		self.BoutonRechercher.connect("clicked", self.on_BoutonRechercher_clicked)
		
		self.LabelAfficher = gtk.Label("    Afficher : ")
		
		self.ListStoreAfficher = liststoreafficher.ListStoreAfficher(self.config, self.fenetre)
		
		self.Afficher = gtk.ComboBox(self.ListStoreAfficher)
		self.Afficher.connect("changed", self.on_Afficher_changed)
		
		self.CellAfficherBut = gtk.CellRendererToggle()
		self.CellAfficherBut.connect("toggled", self.on_Afficher_toggled)
		self.CellAfficher = gtk.CellRendererText()
		
		self.Afficher.pack_start(self.CellAfficherBut, True)
		self.Afficher.pack_start(self.CellAfficher, True)
		self.Afficher.add_attribute(self.CellAfficherBut, 'activatable', 0)
		self.Afficher.add_attribute(self.CellAfficherBut, 'active', 1)
		self.Afficher.add_attribute(self.CellAfficher, 'text', 2)
		
		self.HBoxHaut = gtk.HBox()
		self.HBoxHaut.pack_start(self.LabelRechercher, False, False)
		self.HBoxHaut.pack_start(self.Rechercher, True, True)
		self.HBoxHaut.pack_start(self.BoutonRechercher, False, False)
		self.HBoxHaut.pack_start(self.LabelAfficher, False, False)
		self.HBoxHaut.pack_start(self.Afficher, False, False)
		self.HBoxHaut.set_border_width(5)
		
		#Création de la liste des catégories
		self.BordListeCat = gtk.Frame()
		self.DefilListeCat = gtk.ScrolledWindow()
		self.DefilListeCat.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
		
		self.TreeStoreCat = treestorecat.TreeStoreCat(self.config, self)
		
		self.ListCat = gtk.TreeView(self.TreeStoreCat)
		self.ListCat.connect("cursor-changed", self.on_ListCat_cursor_changed)
		self.ListCat.set_headers_visible(False)
		self.ColonneCat = gtk.TreeViewColumn('Catégorie')
		self.ColonneCat.set_sort_order(gtk.SORT_ASCENDING)
		self.ColonneIcoCat = gtk.TreeViewColumn('')
		self.ListCat.append_column(self.ColonneIcoCat)
		self.ListCat.append_column(self.ColonneCat)
		
		self.CellCatIco = gtk.CellRendererPixbuf()
		self.CellCat = gtk.CellRendererText()
		
		self.ColonneIcoCat.pack_start(self.CellCatIco, True)
		self.ColonneCat.pack_start(self.CellCat, True)
		self.ColonneIcoCat.add_attribute(self.CellCatIco, 'pixbuf', 0)
		self.ColonneCat.add_attribute(self.CellCat, 'text', 1)

		self.DefilListeCat.add(self.ListCat)
		self.BordListeCat.add(self.DefilListeCat)
		
		#Création de la liste des applications
		self.BordListeApps = gtk.Frame()
		self.DefilListeApps = gtk.ScrolledWindow()
		self.DefilListeApps.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
		
		self.ListStoreApps = liststoreapps.ListStoreApps(self.config)
		
		self.CellAppsBut = gtk.CellRendererToggle()
		self.CellAppsBut.set_property('activatable', True)
		self.CellAppsBut.connect("toggled", self.on_CellAppsBut_toggled)
		self.CellAppsIco = gtk.CellRendererPixbuf()
		self.CellApps = gtk.CellRendererText()

		self.ListApps = gtk.TreeView(self.ListStoreApps)
		self.ListApps.connect("cursor-changed", self.on_ListApps_cursor_changed)
		self.ListApps.set_headers_visible(False)
		self.ColonneIcoApps = gtk.TreeViewColumn('')
		self.ColonneApps = gtk.TreeViewColumn('Application', self.CellApps, markup=2)
		self.ColonneApps.set_sort_order(gtk.SORT_ASCENDING)
		self.ColonneBoutonsApps = gtk.TreeViewColumn('')
		self.ListApps.append_column(self.ColonneBoutonsApps)
		self.ListApps.append_column(self.ColonneIcoApps)
		self.ListApps.append_column(self.ColonneApps)
		
		self.ColonneBoutonsApps.pack_start(self.CellAppsBut, True)
		self.ColonneBoutonsApps.add_attribute(self.CellAppsBut, 'active', 0)
		self.ColonneIcoApps.pack_start(self.CellAppsIco, True)
		self.ColonneIcoApps.add_attribute(self.CellAppsIco, 'pixbuf', 1)
		self.ColonneApps.add_attribute(self.CellApps, 'text', 2)

		self.DefilListeApps.add(self.ListApps)
		self.BordListeApps.add(self.DefilListeApps)
		
		#Création de la description de l'application
		self.BordDescApp = gtk.Frame()
		self.DefilDescApp = gtk.ScrolledWindow()
		self.DefilDescApp.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
		self.ViewDescApp = gtk.Viewport()
		self.ViewDescApp.set_shadow_type(gtk.SHADOW_NONE)
		
		self.DescApp = descappbox.DescAppBox(self.config)
		
		self.ViewDescApp.add(self.DescApp)
		self.DefilDescApp.add(self.ViewDescApp)
		self.BordDescApp.add(self.DefilDescApp)
		
		#Création de la zone du bas
		self.HBBoxBas = gtk.HButtonBox()
		self.HBBoxBas.set_layout(gtk.BUTTONBOX_START)
		
		self.BoutonAPropos = gtk.Button(stock = gtk.STOCK_ABOUT)
		self.BoutonAPropos.connect("clicked", self.on_BoutonAPropos_clicked)
		self.HBBoxBas.pack_start(self.BoutonAPropos, False, False)
		self.BoutonPref = gtk.Button(stock = gtk.STOCK_PREFERENCES)
		self.BoutonPref.connect("clicked", self.on_BoutonPref_clicked)
		self.HBBoxBas.pack_start(self.BoutonPref, False, False)
		self.BoutonActualiser = gtk.Button(stock = gtk.STOCK_REFRESH)
		self.BoutonActualiser.connect("clicked", self.on_BoutonActualiser_clicked)
		self.HBBoxBas.pack_start(self.BoutonActualiser, False, False)
		self.HBBoxBas.set_child_secondary(self.BoutonActualiser, True)
		self.BoutonAnnuler = gtk.Button(stock = gtk.STOCK_CANCEL)
		self.BoutonAnnuler.connect("clicked", self.on_BoutonAnnuler_clicked)
		self.HBBoxBas.pack_start(self.BoutonAnnuler, False, False)
		self.HBBoxBas.set_child_secondary(self.BoutonAnnuler, True)
		self.BoutonAppliquer = gtk.Button(stock = gtk.STOCK_APPLY)
		self.BoutonAppliquer.connect("clicked", self.on_BoutonAppliquer_clicked)
		self.HBBoxBas.pack_start(self.BoutonAppliquer, False, False)
		self.HBBoxBas.set_child_secondary(self.BoutonAppliquer, True)
		self.HBBoxBas.set_border_width(5)
		
		
		self.VBoxDroite = gtk.VPaned()
		self.VBoxDroite.add1(self.BordListeApps)
		self.VBoxDroite.add2(self.BordDescApp)
		self.VBoxDroite.set_position(250)
		
		self.HBoxMilieu = gtk.HPaned()
		self.HBoxMilieu.add1(self.BordListeCat)
		self.HBoxMilieu.add2(self.VBoxDroite)
		self.HBoxMilieu.set_position(175)
		self.HBoxMilieu.set_border_width(5)
		
		self.VBoxPrincipale = gtk.VBox()
		self.VBoxPrincipale.pack_start(self.HBoxHaut, False, True)
		self.VBoxPrincipale.pack_start(self.HBoxMilieu, True, True)
		self.VBoxPrincipale.pack_start(self.HBBoxBas, False, False)
				
		self.fenetre.add(self.VBoxPrincipale)
		
		self.fenetre.show_all()
		self.DescApp.hide_all()
		
		self.ListCat.get_selection().select_path((0,))
		self.ListCat.expand_all()
		
		self.ListStoreApps.display_cat(self.TreeStoreCat[(0,)][2])
		
		try:
			self.ListApps.get_selection().select_path((0,))
			self.DescApp.display_app(self.ListStoreApps[(0,)][3])
		except:
			pass
		
	def on_Afficher_changed(self, widget):
		"""Activé quand on clique sur un élément du menu afficher."""
		self.Afficher.set_active(-1)
		return
		
	def on_Afficher_toggled(self, widget, path):
		"""Activé quand on coche un élément du menu afficher."""
		self.Afficher.set_active(-1)
		self.ListStoreAfficher[path][1] = not self.ListStoreAfficher[path][1]
		
		active = self.ListStoreAfficher[path][1]
		name = str(self.ListStoreAfficher[path][2])
		link = self.ListStoreAfficher[path][3]
		if link == "displayinstalled":
			self.config.set('Display', 'DisplayInstalled', active)
			self.ListStoreApps.clear()
			(modele, iter) = self.ListCat.get_selection().get_selected()
			self.ListStoreApps.display_cat(self.TreeStoreCat[modele.get_path(iter)][2])
		elif link == "displayuninstalled":
			self.config.set('Display', 'DisplayUninstalled', active)
			self.ListStoreApps.clear()
			(modele, iter) = self.ListCat.get_selection().get_selected()
			self.ListStoreApps.display_cat(self.TreeStoreCat[modele.get_path(iter)][2])
		else:
			config = ConfigParser.RawConfigParser()
			config.read('list/sources.list')
			config.set(name, 'display', active)
			config.write(open('list/sources.list', 'wb'))
			self.on_BoutonActualiser_clicked()
		
	def on_BoutonActualiser_clicked(self, widget = None):
		"""Actualise les listes."""
		self.config.read_file()
		
		self.ListStoreAfficher.clear()
		self.ListStoreAfficher.import_head()
		self.ListStoreAfficher.import_src_list(self.fenetre)
		
		self.TreeStoreCat.import_src_list()
		self.ListCat.get_selection().select_path((0,))
		self.ListCat.expand_all()
		
		self.ListStoreApps.clear()
		self.ListStoreApps.display_cat(self.TreeStoreCat[(0,)][2])
		try:
			self.ListApps.get_selection().select_path((0,))
			self.DescApp.display_app(self.ListStoreApps[(0,)][3])
		except:
			pass
		
	def on_BoutonAnnuler_clicked(self, widget):
		"""Quitte l'application."""
		self.fenetre.destroy()
		
	def on_BoutonAppliquer_clicked(self, widget):
		"""Applique les modifications."""
		confirm.confirm(self.config, self.modifs)
		
	def on_BoutonAPropos_clicked(self, widget):
		apropos.APropos(self.config)
		return
		
	def on_BoutonPref_clicked(self, widget):
		"""Ouvre les préférences."""
		preferences.Preferences(self.config, self)
		
	def on_BoutonRechercher_clicked(self, widget):
		"""Applique les modifications."""
		self.filtre = self.Rechercher.get_text()
		self.on_ListCat_cursor_changed()
		
	def on_CellAppsBut_toggled(self, cell, path):
		"""Activé quand on coche une application."""
		self.ListStoreApps[path][0] = not self.ListStoreApps[path][0]
		self.ListStoreApps[path][3].set("install", self.ListStoreApps[path][0])
		change = True
		if self.ListStoreApps[path][0] == True:
			self.modifs.add_install(self.ListStoreApps[path][3])
		elif self.ListStoreApps[path][0] == False:
			self.modifs.add_uninstall(self.ListStoreApps[path][3])
		
	def on_fenetre_destroy(self, widget):
		"""Quitte gtk quand l'application est fermée."""
		gtk.main_quit()
		
	def on_ListApps_cursor_changed(self, widget):
		"""Activé quand on selectionne une application."""
		(modele, iter) = self.ListApps.get_selection().get_selected()
		self.DescApp.display_app(self.ListStoreApps[modele.get_path(iter)][3])
		
	def on_ListCat_cursor_changed(self, widget = None):
		"""Activé quand on selectionne une catégorie."""
		self.ListStoreApps.clear()
		(modele, iter) = self.ListCat.get_selection().get_selected()
		self.ListStoreApps.display_cat(self.TreeStoreCat[modele.get_path(iter)][2], self.filtre)

if __name__ == "__main__":
	gtk.gdk.threads_init()
	gtk.gdk.threads_enter()
	
	mconfig = config.Config()
	SynAppsMain(mconfig)
	gtk.main()

	gtk.gdk.threads_leave()
