/* TreeSize for Unix  http://treesize.sf.net/
 * Copyright (c) 2006-2007 Marcos Diez <marcos_AT_unitron.com.br>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 */


#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif
#include <gdk/gdkkeysyms.h>
#include <gdk/gdk.h>
#include <gtk/gtk.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "TSmonitor.h"
#include "callbacks.h"
#include "interface.h"
#include "support.h"

#include "ui-util.h"
#include "TStreeSizeGui.h" 
#define SHOWME  printf("[%s]\n" , __FUNCTION__ );

#define GLADE_HOOKUP_OBJECT(component,widget,name) \
  g_object_set_data_full (G_OBJECT (component), name, \
    gtk_widget_ref (widget), (GDestroyNotify) gtk_widget_unref)

void on_btnOpen_clicked(GtkToolButton *toolbutton, gpointer user_data) {
	GtkWidget *chooseFolder = create_ChooseFolder();
	/* there must be a not so  dirty way of doing it. But this is actually Glade's fault, I think  */
	GLADE_HOOKUP_OBJECT( chooseFolder , lookup_widget( (GtkWidget *) toolbutton , "TVtreeView") , "TVtreeView");
	gtk_widget_show(chooseFolder);
}

void on_btnCFopen_clicked(GtkButton *button, gpointer user_data) {
	GtkFileChooser *ChooseFolder = ( GtkFileChooser *) lookup_widget(
			(GtkWidget *) button , "ChooseFolder");
	GtkTreeView* treeView = ( GtkTreeView *) lookup_widget(
			(GtkWidget *) button , "TVtreeView");
	gchar *theChoosenFolderName = g_filename_to_utf8(
			gtk_file_chooser_get_filename(ChooseFolder) , -1, 0, 0, 0);

	/*   printf("Opening Folder [%s]\n" , (char  *) theChoosenFolderName ); */

	TScalculateSize( (GtkWidget *) treeView , (char *) theChoosenFolderName );
	/*   g_object_unref( theChoosenFolderName ); */
	g_free(theChoosenFolderName);
	gtk_widget_destroy( (GtkWidget *) ChooseFolder );

}

void on_btnReload_clicked(GtkToolButton *toolbutton, gpointer user_data) {
	GtkWidget *treeView =
			lookup_widget( (GtkWidget *) toolbutton , "TVtreeView");
	GtkWidget *entFolder=lookup_widget( (GtkWidget *) toolbutton , "entFolder");
	TScalculateSize( (GtkWidget *) treeView ,
			(char *) gtk_entry_get_text( (GtkEntry *) entFolder ) );
}

void on_btnCancel_clicked(GtkToolButton *toolbutton, gpointer user_data) {
	TSrunning=0;
	gtk_widget_set_sensitive( (GtkWidget *)toolbutton, FALSE);
}

void store_filename(GtkWidget *widget, gpointer user_data) {
	GtkWidget *file_selector = GTK_WIDGET(user_data);
	const gchar *selected_filename;

	selected_filename
			= gtk_file_selection_get_filename(GTK_FILE_SELECTION(file_selector));
	g_print("Selected filename: %s\n", selected_filename);
}

void create_file_selection(void) {

	GtkWidget *file_selector;

	/* Create the selector */

	file_selector = gtk_file_selection_new("Please select a file for editing.");

	g_signal_connect(GTK_FILE_SELECTION (file_selector)->ok_button, "clicked", G_CALLBACK(store_filename),
			file_selector);

	/* Ensure that the dialog box is destroyed when the user clicks a button. */

	g_signal_connect_swapped(GTK_FILE_SELECTION (file_selector)->ok_button, "clicked",
			G_CALLBACK(gtk_widget_destroy), file_selector);

	g_signal_connect_swapped(GTK_FILE_SELECTION (file_selector)->cancel_button, "clicked",
			G_CALLBACK(gtk_widget_destroy), file_selector);

	/* Display that dialog */

	gtk_widget_show(file_selector);
}

GdkPixbuf* gdkTreeSize;
void on_btnAbout_clicked(GtkToolButton *toolbutton, gpointer user_data) {
	GtkWidget *aboutDialog = create_AboutDialog();
	gtk_window_set_modal(GTK_WINDOW(aboutDialog), TRUE);
	gtk_about_dialog_set_logo(GTK_ABOUT_DIALOG(aboutDialog) , gdkTreeSize);
	gtk_widget_show(aboutDialog);
}

void on_TVtreeView_row_activated(GtkTreeView *treeview, GtkTreePath *path,
		GtkTreeViewColumn *column, gpointer user_data) {
	if (gtk_tree_view_row_expanded(treeview, path) ) {
		gtk_tree_view_collapse_row(treeview, path);
	} else {
		gtk_tree_view_expand_row(treeview, path, 0);
	}
}

static int initialEntFolderSize=0;

void on_mainWindow_size_allocate(GtkWidget *widget, GdkRectangle *allocation,
		gpointer user_data) {
	GtkWidget *entFolder=lookup_widget(widget, "entFolder");
	if (initialEntFolderSize) {
		int newSize = allocation->width - initialEntFolderSize;
		if (newSize > 50) {
			gtk_widget_set_size_request(entFolder, allocation->width
					- initialEntFolderSize, -1);
		}
	} else {
		GtkRequisition actualSize;
		gtk_widget_size_request(entFolder, &actualSize);
		initialEntFolderSize=allocation->width - actualSize.width;
	}
}

void on_btnOnlyeOnFileSystem_toggled(GtkToggleButton *menuitem, gpointer user_data) {
	


	gboolean onlyOneFileSystem =
		gtk_toggle_tool_button_get_active( (GtkToggleToolButton *) menuitem );
	printf("%s %p %d %d\n", __FUNCTION__, menuitem, (int) user_data ,
			(int) onlyOneFileSystem );

}


gboolean
on_TVtreeView_key_press_event(GtkWidget *widget, GdkEventKey *event,
		gpointer user_data) {

  switch(event->keyval)
    {
    case GDK_Left:
    case GDK_KP_Left:
    case GDK_Right:
    case GDK_KP_Right:
      {
	GtkTreeView *treeView = (GtkTreeView *) widget;
	GtkTreeSelection *selection=  gtk_tree_view_get_selection( treeView );
	GtkTreeIter iter;
	GtkTreeModel *model=0;
	gboolean isSomethingSelected = gtk_tree_selection_get_selected( selection , &model , &iter );
	if( ! isSomethingSelected )	return TRUE;
	GtkTreePath* treePath = gtk_tree_model_get_path( model , &iter );

	gboolean rowIsExpanded=gtk_tree_view_row_expanded( treeView , treePath );
	if( event->keyval == GDK_Left || event->keyval == GDK_KP_Left ){
	  if( rowIsExpanded ){
	    gtk_tree_view_collapse_row ( treeView , treePath );
	  }else{
	    gtk_tree_path_up ( treePath );
	    gtk_tree_view_set_cursor( treeView , treePath , 0 , FALSE );
	  }
	}else{ // GDK_Right or KP_Right
	  if( rowIsExpanded ){
	    gtk_tree_path_down ( treePath );
	    gtk_tree_view_set_cursor( treeView , treePath , 0 , FALSE );
	  }else{
	    gtk_tree_view_expand_row ( treeView , treePath ,  0 );
	  }
	}
	gtk_tree_path_free( treePath );

	return TRUE;
      }
    default:
      break;
    };
  

  return FALSE;
}
 

gboolean on_entFolder_key_press_event(GtkWidget *widget, GdkEventKey *event,
		gpointer user_data) {
	if (event->keyval == GDK_Return) {
		GtkWidget *treeView=lookup_widget(widget, "TVtreeView");

		TScalculateSize( (GtkWidget *) treeView ,
				(char *) gtk_entry_get_text( (GtkEntry *) widget ) );

	}
	if (event->state & GDK_CONTROL_MASK && event->keyval == GDK_u) {
		/* control U clears the string */
		gtk_entry_set_text( (GtkEntry *) widget , "");

		/* 			lookup_widget( treeView , "entFolder" ) , (const gchar * ) absoluteDirName ); */

	}

	return FALSE;
}

extern GtkMenu *TreeSizeMenuGlobal;




gboolean
on_TVtreeView_button_press_event(GtkWidget *widget,
				 GdkEventButton *event, gpointer user_data) {

	GdkEventButton *event_button;

	g_return_val_if_fail(widget != NULL, FALSE);
	g_return_val_if_fail(event != NULL, FALSE);

	if (event->type == GDK_BUTTON_PRESS) {
		event_button = (GdkEventButton *) event;
		if (event_button->button == 3) {
			if ( !getTVSelectedValue(COL_PATH) ) { /* something MUST be selected for the user to become a menu */
				return FALSE;
			}
			gtk_menu_popup(TreeSizeMenuGlobal, NULL, NULL, NULL, NULL,
					event_button->button, event_button->time);
			return TRUE;
		}
	}

	return FALSE;
}

void on_TVtreeView_cursor_changed(GtkTreeView *treeview, gpointer user_data) {
	statusBar_write(getTVSelectedValue(COL_PATH) );
	/*   printf("blah %c\n"  , *((char *) user_data )+1); */
}

void on_menuCopy_folder_path_activate(GtkMenuItem *menuitem, gpointer user_data) {
	char *folderPath = (char *) getTVSelectedValue(COL_PATH);
	if ( !folderPath)
		return;
	{
		char *folderPathUTF8 = g_filename_to_utf8(folderPath, -1, 0, 0, 0);
		gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD),
				folderPathUTF8, -1);
		g_free(folderPathUTF8);

	}
}

extern GtkWidget *mainWindow;
void on_menuOpen_activate(GtkMenuItem *menuitem, gpointer user_data) {
	char *folderPath = (char *) getTVSelectedValue(COL_PATH);
	if (folderPath) {
		if ( !fork() ) {
			/* file managers, in order of preference.... */
			execlp("xdg-open", "xdg-open", folderPath, (char *) NULL );
			execlp("thunar", "thunar", folderPath,  (char *) NULL );
			execlp("konqueror", "konqueror", folderPath, (char *) NULL );
			execlp("nautilus", "nautilus", folderPath, (char *) NULL );
			{
				char *errormsg=
						"ERROR: TreeSize for Unix could not launch any of the following\n"
							"file managers: \n"
							"xdg-open ( standard call sugested by http://freedesktop.org )\n"
							"thunar\n"
							"konqueror\n"
							"nautilus\n"
							"Please install any of them and verify that they are in your path.";
				execlp("xmessage", "xmessage", errormsg, (char *) NULL );
			}

			exit(0);
		}
	}
}

void on_menuXtermHere_activate(GtkMenuItem *menuitem, gpointer user_data) {
	char *folderPath = (char *) getTVSelectedValue(COL_PATH);
	if (chdir(folderPath) == -1) {
		GtkWidget *dialog = gtk_message_dialog_new( (GtkWindow *) mainWindow ,
				GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR,
				GTK_BUTTONS_CLOSE,
				"Error opening a xterm window on folder '%s'", folderPath);
		gtk_dialog_run(GTK_DIALOG(dialog));
		gtk_widget_destroy(dialog);

	} else {
		if ( !fork() ) {
			char *term;
			term = "xdg-terminal";
			execlp(term, term, 0, (char *) NULL );
			term = "terminal";
			execlp(term, term, 0, (char *) NULL );
			term = "gnome-terminal";
			execlp(term, term, 0, (char *) NULL );
			term = "konsole";
			execlp(term, term, 0, (char *) NULL );
			term = "Eterm";
			execlp(term, term, 0, (char *) NULL );
			term = "xterm";
			execlp(term, term, 0, (char *) NULL );
			term = "rxvt";
			execlp(term, term, 0, (char *) NULL );
			{
				char *errormsg=
						"ERROR: TreeSize for Unix could not open any of the following\n"
							"terminal emulators:\n"
							"xdg-terminal ( standard call sugested by http://freedesktop.org )\n"
							"terminal\n"
							"gnome-terminal\n"
							"Eterm\n"
							"xterm\n"
							"rxvt\n"
							"Please install any of them and verify that they are in your path.";
				execlp("xmessage", "xmessage", errormsg, (char *) NULL );
			}

			exit(0);
		}
	}
}

void on_menuDelete_activate(GtkMenuItem *menuitem, gpointer user_data) {
	char *folderPath = (char *) getTVSelectedValue(COL_PATH);
	printf("%s NOT YET IMPLEMENTED\n", __FUNCTION__);
	if ( !folderPath)
		return;
}
