# Bryan Schumaker (June 2010)

import ocarina
import gobject
import os

gtk      = ocarina.gtk
libsaria = ocarina.libsaria
threads  = libsaria.threads

#FS_OK = gobject.signal_new("filesystem_ok", gtk.FileChooserDialog,
#		gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
#		(gtk.Dialog, int))
#print FS_OK

#print gobject.signal_query(FS_OK)
#print gobject.signal_query(gtk.RESPONSE_OK)
chooser_window = None
chooser_widget = None

def make_chooser(title, action):
	buttons = (gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OK, gtk.RESPONSE_OK)
	chooser = gtk.FileChooserDialog(title, action=action, buttons=buttons)
	return chooser

def make_chooser2(title, callback):
	global chooser_window
	global chooser_widget
	chooser_window = gtk.Window(gtk.WINDOW_TOPLEVEL)

	chooser_box = gtk.VBox(spacing = 0)
	button_box  = gtk.HBox()
	chooser_widget = gtk.FileChooserWidget()
	open_button    = gtk.Button(stock=gtk.STOCK_OK)
	close_button   = gtk.Button(stock=gtk.STOCK_CANCEL)
	button_box.pack_end(open_button, False, False, 10)
	button_box.pack_end(close_button, False, False)
	chooser_box.pack_start(chooser_widget, True, True, 10)
	chooser_box.pack_start(button_box, False, False, 10)

	size = close_button.size_request()
	open_button.set_size_request(size[0], size[1])
	chooser_widget.connect("file-activated", select_path, callback)
	open_button.connect("clicked", select_path, callback)
	close_button.connect("clicked", hide_chooser)

	chooser_window.add(chooser_box)
	chooser_window.resize(800, 600)
	chooser_window.show_all()

def hide_chooser(button):
	global chooser_window
	chooser_window.hide()

def select_path(widget, callback):
	global chooser_widget
	global chooser_window
	chooser_window.hide()
	uri = chooser_widget.get_uri()
	if uri[:7] == "file://":
		uri = uri[7:]
	uri = uri.replace("%20", " ")
	callback(uri)

def run_chooser2(callback):
	make_chooser2("title", callback)

def run_chooser(chooser):
	file = None
	if chooser.run() == gtk.RESPONSE_OK:
		file = chooser.get_filename()
	chooser.hide()
	return file

# Use for selecting a file through the GUI
def select_file(title = "Select a song"):
	chooser = make_chooser(title, gtk.FILE_CHOOSER_ACTION_OPEN)
	return run_chooser(chooser)

# Use for selecting a directory through the GUI
def select_dir(title = "Select a directory"):
	chooser = make_chooser(title, gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)
	return run_chooser(chooser)

def select_save(title = "Select a location"):
	chooser = make_chooser(title, gtk.FILE_CHOOSER_ACTION_SAVE)
	return run_chooser(chooser)
