#include <fileselect.h>

#ifdef HAVE_GTK_FILE_CHOOSER_DIALOG_NEW 

void _fileselect(GtkWidget *w, gpointer d, GtkFileChooserAction action) {
	GtkWidget *dialog;
	void (*func)(const char *);
	char *filename = NULL;

	dialog = gtk_file_chooser_dialog_new (((GString *)(((gpointer *)d)[2]))->str, NULL, action, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL);
	gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(dialog), ((GString *)(((gpointer *)d)[1]))->str);

	if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT)
    filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));

	gtk_widget_destroy (dialog);

	if (filename != NULL) {
		func = (((gpointer *)d)[0]);
		func(filename);

    g_free (filename);
	}
}

void fileselect(GtkWidget *w, gpointer d) {
	_fileselect(w, d, GTK_FILE_CHOOSER_ACTION_OPEN);
}

void dirselect(GtkWidget *w, gpointer d) {
	_fileselect(w, d, GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER);
}

#else

void fileselect_cancel_callback(GtkWidget *w, gpointer d) {
	gtk_widget_destroy((GtkWidget *)(((gpointer *)d)[0]));
	g_free ((gpointer *)d);
}

void fileselect_ok_callback(GtkWidget *w, gpointer d) {
	GString *filename;
	void (*func)(const char *);

	filename = g_string_new(gtk_file_selection_get_filename (GTK_FILE_SELECTION ((GtkWidget *)(((gpointer *)d)[0]))));

	fileselect_cancel_callback (w, d);
	
	func = (((gpointer *)d)[1]);
	func(filename->str);

	g_string_free(filename, TRUE);
}

void _fileselect(GtkWidget *w, gpointer d) {
	gpointer *eles;

	eles = g_malloc(sizeof(gpointer) * 2);

	eles[0] = (gpointer *)gtk_file_selection_new (((GString *)(((gpointer *)d)[2]))->str);
	eles[1] = ((gpointer *)d)[0];
	gsc(GTK_FILE_SELECTION ((GtkWidget *)eles[0])->ok_button, "clicked", fileselect_ok_callback, (gpointer)eles);
	gsc(GTK_FILE_SELECTION ((GtkWidget *)eles[0])->cancel_button, "clicked", fileselect_cancel_callback, (gpointer)eles);
	gtk_window_set_modal(GTK_WINDOW((GtkWidget *)eles[0]), TRUE);
	gtk_file_selection_set_filename(GTK_FILE_SELECTION((GtkWidget *)(((gpointer *)eles)[0])),
			((GString *)((gpointer *)d)[1])->str);
	gtk_widget_show ((GtkWidget *)eles[0]);
}

void fileselect(GtkWidget *w, gpointer d) {
	_fileselect(w, d);
}

void dirselect(GtkWidget *w, gpointer d) {
	_fileselect(w, d);
}

#endif
