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

import gtk, pathutils, os.path, re

class FileChooserEntry(gtk.HBox):
	"""gtk.Entry avec un bouton Parcourir"""
	def __init__(self, config, title=None, framaroot=False, action=gtk.FILE_CHOOSER_ACTION_OPEN):
		self.config = config
		self.framaroot = framaroot
		gtk.HBox.__init__(self)
		
		self.entry = gtk.Entry()
		self.pack_start(self.entry, True, True)
		
		self.button = gtk.Button()
		image = gtk.Image()
		image.set_from_stock(gtk.STOCK_OPEN, gtk.ICON_SIZE_MENU)
		self.button.set_image(image)
		self.button.connect("clicked", self.browse)
		self.pack_start(self.button, False, False)
		
		if action == gtk.FILE_CHOOSER_ACTION_OPEN or action == gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER:
			buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)
		else:
			buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)
		
		self.dialog = gtk.FileChooserDialog(title, None, action, buttons)
		
	def browse(self, widget=None):
		if self.framaroot:
			self.dialog.set_filename(os.path.join(self.config.get("FramaKioskTune", "FramaRoot"), re.sub("FramaRoot/", "", self.entry.get_text().replace("\\", "/"))))
		else:
			self.dialog.set_filename(os.path.join(self.config.get("FramaKioskTune", "FramaKioskPath") + "/Data/FramaKiosk/", self.entry.get_text()))
		rep = self.dialog.run()
		
		if rep == gtk.RESPONSE_OK:
			if self.framaroot:
				self.entry.set_text("Framaroot\\" + pathutils.relpath(self.config.get("FramaKioskTune", "FramaRoot"), self.dialog.get_filename()).replace("/", "\\"))
			else:
				self.entry.set_text(pathutils.relpath(self.config.get("FramaKioskTune", "FramaKioskPath") + "/Data/FramaKiosk/", self.dialog.get_filename()))
		self.dialog.hide()
		
	def set_filename(self, filename):
		self.entry.set_text(filename)
		
	def get_filename(self):
		return self.entry.get_text()
