#include "../../src/skipstone.h"

static void create_plugin(SkipStone *ss);

static SkipStonePlugin plugin =
{
   "Up",
     PLUGIN_IN_TOOLBAR_START,
     create_plugin,
     NULL,
     NULL,
     1
};

static void on_button_click(GtkWidget *b, SkipStone *ss);
static gchar *get_up_url(gchar *location);


static void on_button_click(GtkWidget *b, SkipStone *ss)
{
   
   gchar *location, *up;
   location = gtk_moz_embed_get_location(ss->embed);
   if (!location) 
     {
	skipstone_error_dialog("Up Plugin Error","Couldn't go up!",FALSE);
	return;
     }
   up = get_up_url(location);
   
   /*g_print("got up url %s from %s\n",up, location);*/
   
   if (up) {
/*      g_print("going up: %s\n", up);*/
      skipstone_load_url_cb(ss, up);
      g_free(up);
   }
   
   g_free(location);
   return;
	
   
}

static gchar *prefixes[] = 
{
     "http://",
     "ftp://",
     "https://",
     "file:///",
     NULL
};


static gchar *get_up_url(gchar *location)
{
   gchar *s, *a, *p = NULL, *r = NULL;
   gint i, l;

   a = g_strdup(location);
   s = a;
   
   for (i = 0; prefixes[i] != NULL; ++i) 
     {
	if (!g_strncasecmp(location,prefixes[i], strlen(prefixes[i])))
	  {
	     s += strlen(prefixes[i]);
	     p = prefixes[i];
	     break;
	  }
     }

/*      g_print("after stripping we got %s from %s\n",s,location);*/
   
   l = strlen(s);
   
   if (s[l-1] == '/') /* this is a directory and not a file, lets try to go up if we can */
     {
	s[l-1] = '\0'; /* end here */
/*	g_print("its a directory %s\n",s);*/
     } 
   else 
     {
/*	g_print("its a file %s - stripping\n",s);*/
		  
	for (i=l; i >  0 ; i--) 
	  {
	     if (s[i-1] == '/') {		
		s[i] = '\0';
		break;
	     }
	     
	  }
/*       g_print("fixed file %s\n",s); */
     }
   
   for (i = l; i > 0 ; i--) 
     {
	if (s[i-1] == '/') 
	  {
	     s[i] = '\0'; /* end it here then */
	     if (p == NULL) {
		  r = g_strdup(s);
	     } else {
		  r = g_strconcat(p,s, NULL);
	     }
/*	     g_print("returning %s\n",r);*/
	     break;
	  }
     }
   
   g_free(a);
   return r;
}


static void create_plugin(SkipStone *ss)
{
   GtkWidget *button, *pix;
   gint loaded=0;
     
   button = gtk_button_new();
   pix = create_pixmap(button, "up.png", &loaded);
   if (!loaded) {
	g_print("Could not find up.xpm please place it in SkipStone's theme dir\n");
	gtk_widget_destroy(GTK_WIDGET(button));
	button = gtk_button_new_with_label("Up");
   } else {
	gtk_container_add(GTK_CONTAINER(button), pix);
   }
   gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE); 
   gtk_signal_connect(GTK_OBJECT(button), "clicked",
			GTK_SIGNAL_FUNC(on_button_click),
			ss);
   gtk_widget_show(button);   
   skipstone_add_plugin_to_toolbar(ss, button, 
				   "Click here to go up a directory / level");
   
}

SkipStonePlugin * init_plugin(void)
{
   return &plugin;
}
