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

import gtk, gobject, os.path
from lib import notebookimg, scrollframe, urlstuff

def str2bool(v):
  return v.lower() in ("yes", "true", "t", "1")
  
class preferences(gtk.Dialog):
	def __init__(self, db, parent):
		self.db = db
		
		gtk.Dialog.__init__(self, "SynApps - Préférences", parent, gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT|	gtk.DIALOG_NO_SEPARATOR, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_APPLY, gtk.RESPONSE_OK))
		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)
		
		#Création des onglets
		self.notebook = notebookimg.NoteBookImg()
		self.get_content_area().pack_start(self.notebook)
		
		# Création de l'onglet Général
		self.general = gtk.Table(7, 2)
		self.general.set_border_width(5)
		
		self.appspathlabel = gtk.Label("<b>Dossier apps : </b>")
		self.appspathlabel.set_use_markup(True)
		
		self.appspathdialog = gtk.FileChooserDialog("Dossier Apps", self, gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
		
		#self.appspathdialog.set_filename(self.db.get_config("appspath", ""))
		self.appspathentry = gtk.FileChooserButton(self.appspathdialog)
		self.appspathentry.set_current_folder(self.db.get_config("appspath", ""))#.set_current_folder('/etc')
		
		self.proxycheckbox = gtk.CheckButton("Utiliser un proxy (expérimental !)")
		self.proxycheckbox.set_active(str2bool(self.db.get_config("proxycheckbox", False)))
		self.proxycheckbox.connect("toggled", self.toggle)
		self.proxyhostlabel = gtk.Label("Adresse :")
		self.proxyhostlabel.set_alignment(0,0.5)
		self.proxyhostval = gtk.Entry(0)
		self.proxyhostval.set_text(self.db.get_config("proxyhost", ""))
		self.proxyportlabel = gtk.Label("Port :")
		self.proxyportlabel.set_alignment(0,0.5)
		self.proxyportval = gtk.Entry(0)
		self.proxyportval.set_text(str(self.db.get_config("proxyport", "")))
		self.proxyloginlabel = gtk.Label("Identifiant :")
		self.proxyloginlabel.set_alignment(0,0.5)
		self.proxyloginval = gtk.Entry(0)
		self.proxyloginval.set_text(self.db.get_config("proxylogin", ""))
		self.proxypasslabel = gtk.Label("Mot de passe :")
		self.proxypasslabel.set_alignment(0,0.5)
		self.proxypassval = gtk.Entry(0)
		self.proxypassval.set_text(self.db.get_config("proxypass", ""))
		self.proxypassval.set_visibility(False)

		self.general.attach(self.appspathlabel, 0, 1, 0, 1, gtk.FILL, gtk.FILL)
		self.general.attach(self.appspathentry, 1, 2, 0, 1, gtk.FILL|gtk.EXPAND, gtk.FILL)
		self.general.attach(self.proxycheckbox, 0, 1, 2, 3, gtk.FILL, gtk.FILL)
		self.general.attach(self.proxyhostlabel, 0, 1, 3, 4, gtk.FILL, gtk.FILL)
		self.general.attach(self.proxyportlabel, 0, 1, 4, 5, gtk.FILL, gtk.FILL)
		self.general.attach(self.proxyloginlabel, 0, 1, 5, 6, gtk.FILL, gtk.FILL)
		self.general.attach(self.proxypasslabel, 0, 1, 6, 7, gtk.FILL, gtk.FILL)
		self.general.attach(self.proxyhostval, 1, 2, 3, 4, gtk.FILL, gtk.FILL)
		self.general.attach(self.proxyportval, 1, 2, 4, 5, gtk.FILL, gtk.FILL)
		self.general.attach(self.proxyloginval, 1, 2, 5, 6, gtk.FILL, gtk.FILL)
		self.general.attach(self.proxypassval, 1, 2, 6, 7, gtk.FILL, gtk.FILL)
		
		self.notebook.append_page(self.general, "Général", "icons/pref-general.png")
				
		# Création de l'onglet Sources
		self.srcvbox = gtk.VBox()
		self.srcvbox.set_border_width(5)
		
		scroll = scrollframe.scrollframe()
		
		self.srclist = source_list(db)
		self.srclist.connect("row-activated", self.edit)
		scroll.add_with_viewport(self.srclist)
		self.srcvbox.pack_start(scroll, True, True)
		
		self.hbboxsrc = gtk.HButtonBox()
		self.hbboxsrc.set_layout(gtk.BUTTONBOX_END)
		
		self.delbut = gtk.Button(stock = gtk.STOCK_REMOVE)
		self.delbut.connect("clicked", self.srclist.delete_selection)
		self.hbboxsrc.pack_start(self.delbut, False, False)
		self.hbboxsrc.set_child_secondary(self.delbut, True)
		self.addbut = gtk.Button(stock = gtk.STOCK_ADD)
		self.addbut.connect("clicked", self.add_new)
		self.hbboxsrc.pack_start(self.addbut, False, False)
		
		self.srcvbox.pack_start(self.hbboxsrc, False, False)
		
		self.notebook.append_page(self.srcvbox, "Sources", "icons/pref-sources.png")
	
	def toggle(self, widget):
		if widget.get_active():
			self.proxyhostlabel.show()
			self.proxyhostval.show()
			self.proxyportlabel.show()
			self.proxyportval.show()
			self.proxyloginlabel.show()
			self.proxyloginval.show()
			self.proxypasslabel.show()
			self.proxypassval.show()
		else:
			self.proxyhostlabel.hide()
			self.proxyhostval.hide()
			self.proxyportlabel.hide()
			self.proxyportval.hide()
			self.proxyloginlabel.hide()
			self.proxyloginval.hide()
			self.proxypasslabel.hide()
			self.proxypassval.hide()
	
	def run(self):
		self.show_all()
		self.toggle(self.proxycheckbox)
		response = gtk.Dialog.run(self)
		
		if response == gtk.RESPONSE_OK:
			self.db.set_config("appspath", os.path.relpath(self.appspathentry.get_filename()))
			self.db.set_config("proxycheckbox", self.proxycheckbox.get_active())
			self.db.set_config("proxyhost", self.proxyhostval.get_text())
			self.db.set_config("proxyport", self.proxyportval.get_text())
			self.db.set_config("proxylogin", self.proxyloginval.get_text())
			self.db.set_config("proxypass", self.proxypassval.get_text())
			# Mise en place du proxy
			if self.proxycheckbox.get_active():
				urlstuff.proxydef(self.proxyhostval.get_text(), int(self.proxyportval.get_text()), self.proxyloginval.get_text(), self.proxypassval.get_text())
			else:
				urlstuff.proxydel()
			
			try:
				urlstuff.urlopen('http://files.framakey.org/index.html')
			except urlstuff.ConnectError:
				dialog = gtk.MessageDialog(self, gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, "Erreur, votre connexion Internet n'a pas l'air de fonctionner.\nVeuillez vérifier le paramétrage du proxy dans les préférences")
				dialog.run()
				dialog.destroy()
				response = gtk.RESPONSE_CANCEL
			else:
				self.db.remove_all()
				self.db.remove_src()
				self.srclist.store.foreach(self.new_src)
		
		return response
	
	def new_src(self, store, path, iter):
		try:
			self.db.add_src(store[path][2], store[path][0])
		except IOError as message:
			dialog = gtk.MessageDialog(self, gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, str(message))
			dialog.run()
			dialog.destroy()
	
	def edit(self, widget, path, column):
		dialog = edit_dialog(self, "Modifier", self.srclist.store[path][2])
		url = dialog.run()
		dialog.destroy()
		
		if url != None:
			self.srclist.store[path][2] = url
	
	def add_new(self, widget):
		dialog = edit_dialog(self)
		url = dialog.run()
		dialog.destroy()
		
		if url != None:
			self.srclist.store.add_source(url)

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

		gtk.TreeView.__init__(self, self.store)
		self.set_headers_visible(False)
		
		cellbut = gtk.CellRendererToggle()
		cellbut.set_property('activatable', True)
		cellbut.connect("toggled", self.toggle)
		cellname = gtk.CellRendererText()
		cellurl = gtk.CellRendererText()
				
		columnbut = gtk.TreeViewColumn('')
		columnbut.pack_start(cellbut, True)
		columnbut.add_attribute(cellbut, 'active', 0)
		self.append_column(columnbut)
		columnname = gtk.TreeViewColumn('')
		columnname.pack_start(cellname, True)
		columnname.add_attribute(cellname, 'text', 1)
		self.append_column(columnname)
		columnurl = gtk.TreeViewColumn('')
		columnurl.pack_start(cellurl, True)
		columnurl.add_attribute(cellurl, 'text', 2)
		self.append_column(columnurl)

	def toggle(self, widget, path):
		self.store[path][0] = not self.store[path][0]
		
	def delete_selection(self, widget):
		(store, iter) = self.get_selection().get_selected()
		if iter != None:
			self.store.remove(iter)

class source_store(gtk.ListStore):
	def __init__(self, db):
		gtk.ListStore.__init__(self, gobject.TYPE_BOOLEAN, str, str)
		gtk.ListStore.set_sort_column_id(self, 1, gtk.SORT_ASCENDING)
		
		for source in db.get_sources():
			self.append([source["active"], source["name"], source["url"]])
	
	def add_source(self, url):
		self.append([True, "Dépôt", url])

class edit_dialog(gtk.Dialog):
	def __init__(self, parent, action="Ajouter", url=""):
		gtk.Dialog.__init__(self, action + " un dépôt", parent, gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT|gtk.DIALOG_NO_SEPARATOR, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_APPLY, gtk.RESPONSE_OK))
		self.set_icon(gtk.gdk.pixbuf_new_from_file("icons/SynApps16.png"))
		self.set_border_width(5)
		#self.set_default_size(400, 300)
		
		label = gtk.Label()
		label.set_use_markup(True)
		label.set_markup("<b>Adresse du dépôt :</b>")
		label.set_alignment(0.0, 0.5)
		
		self.get_content_area().pack_start(label, False, False)
		
		self.entry = gtk.Entry()
		self.entry.set_text(url)
		
		self.get_content_area().pack_start(self.entry, False, True)
		
		self.show_all()
	
	def run(self):
		response = gtk.Dialog.run(self)
		
		if response == gtk.RESPONSE_OK:
			return self.entry.get_text()
		else:
			return None
