/* copyright    Maher Awamy <muhri@muhri.net>           *
 *              Charlie Schmidt <ishamael@themes.org>   *
 *                                                      *
 *  released under the GPL                              */

/* just for koef !! */

#include "skipstone.h"

extern ConfigData config;
static void on_go_menu_activate(GtkWidget *menu_item, SkipStone *skipstone);
static gboolean check_for_dupe(GoMenu *gm, gchar *title);

GoMenu * go_menu_init(void)
{

	GoMenu *go_menu;
     	D_ENTER;
	go_menu = g_new0(GoMenu,1);
	go_menu->menu = gtk_menu_new();
	go_menu->items = NULL;
	gtk_widget_show(go_menu->menu);
	D_RETURN_ (go_menu);
	
}

void go_menu_append(GoMenu *go_menu, gchar *location,  SkipStone *skipstone)
{
	gchar *title;
	GtkWidget *menu_item;
	gboolean add_it;
	gint list_length;

	D_ENTER;
	g_return_if_fail(go_menu != NULL);
	if (!location || location == NULL) D_RETURN;

	if (!skipstone->title || !strcmp(skipstone->title,""))
		title = location; /* no title? use the url */

	if (!strcmp(location,"about:blank")) 	D_RETURN; /* dont add that! */
	
     	add_it = check_for_dupe(go_menu,skipstone->title);
	if (!add_it) 
		D_RETURN;	
	
	menu_item = gtk_menu_item_new_with_label(skipstone->title);
	g_object_set_data_full(G_OBJECT(menu_item), "url", 
				 g_strdup(location),				
				 (GtkDestroyNotify)g_free);
	g_signal_connect(G_OBJECT(menu_item), "activate",
			   G_CALLBACK(on_go_menu_activate), 
			   skipstone);
			   
	gtk_widget_show(menu_item);

	list_length = g_slist_length(go_menu->items);
	
	if (list_length + 1 > config.max_go) {
		GtkWidget *first_item = g_slist_nth_data(go_menu->items, list_length-1);
		go_menu->items = g_slist_remove (go_menu->items, first_item);
		gtk_widget_destroy(first_item);
	}
	
	gtk_menu_prepend(GTK_MENU(go_menu->menu), menu_item);	
	go_menu->items = g_slist_prepend(go_menu->items, menu_item);

	D_RETURN;
}


static void on_go_menu_activate(GtkWidget *menu_item, SkipStone *skipstone)
{
	gchar *url;
     	D_ENTER;
	if (config.notebook || skipstone->is_notebook)
	  skipstone = get_current_browser_from_notebook();
	if (!skipstone) D_RETURN;
	url = g_object_get_data(G_OBJECT(menu_item), "url");
	if (url)
	  _skipstone_load_url(skipstone, url);
	D_RETURN;
}

static gboolean check_for_dupe(GoMenu *gm, gchar *title)
{
	GSList *l;     	
     	D_ENTER;
     	if (!title || title == NULL) D_RETURN_(FALSE);
	for (l = gm->items; l; l = l->next) {
		gchar *text;
		if (!l->data || l->data == NULL) continue;
		text = GTK_LABEL(GTK_BIN(l->data)->child)->label;
	        if (text && !strcmp(title,text)) 
		  D_RETURN_(FALSE);
        }
        D_RETURN_ (TRUE);
}
