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


#include "skipstone.h"

extern GSList *window_count;
extern ConfigData config;
extern GList *combo_urls;
GtkWidget *popupmenu; /* taemporarly here so we can destory it from each call */
extern GList *bookmarks;


gboolean
open_uri (const char *uri)
{
  	pid_t pid;
	int status;
	gboolean process;
     
     	if (!strncmp (uri, "mailto:", 7)) {
		if (!config.mailer) { 
		     g_warning("Configure your mailer please!");
		     return FALSE;
		}
	     	pid = fork ();
		switch (pid) {
		case -1:
			/* error */
			g_warning ("fork() failed");
			break;
		case 0:
			/* child process */
			execlp (config.mailer,config.mailer, uri, NULL);
			break;
		default:
			/* parent process */
			waitpid (pid, &status, WNOHANG);
	     		return TRUE;
		}
	
	} else {
		process = process_uri(uri);
	     	return process;
	}
 	    return FALSE;
}

static const struct
{
     gchar *ext;
     gint length;
}
types[] =
{
       { ".tar.gz", 7},
       { ".tar.bz2", 8},
       { ".rpm",4},
       { ".deb",4},
       { ".zip", 4},
       { ".bz2", 4},
       { ".gz", 3},
       { ".exe", 4},
       { ".bin", 4},
       { NULL, 0}
};

gboolean process_uri(const gchar *uri)
{
     gint i;
     gboolean download;
     for (i = 0; types[i].ext != NULL; i++) {	  
     		if (!strcmp(uri + strlen (uri) - types[i].length , types[i].ext)) {
	       		download = download_url(uri);
     			return download;
		}
     	}
	return FALSE;
}

gboolean download_url(const gchar *uri)
{
	pid_t pid;
	int status;	
     
	if (!config.downloader) {
		     g_warning("Configure your download program");
		     return FALSE;
       	}
	     	pid = fork();
	     	switch (pid) {
		 case -1:
		     g_warning("fork of download failed");
		     break;
		 case 0:
	      		execlp (config.downloader,config.downloader, uri, NULL);
		        break;
		 default:
		     	waitpid (pid, &status, WNOHANG);
		     return TRUE;
		}
	     	     
	return FALSE;				    
}
				    
gint
progress(Bdata *bdata)
{
	gfloat val;

	val = gtk_progress_get_value(GTK_PROGRESS(bdata->progressbar)) + 1;
     	gtk_progress_set_value(GTK_PROGRESS(bdata->progressbar), val);
     	return(TRUE);
}


void 
read_config() 
{
	FILE *config_file;
	gchar *home;
	gchar *file;
	gchar *line;


	home = getenv("HOME");
     	file = g_strconcat(home,"/.skipstonerc", NULL);
  	/* defaults */   	
     	config.home = g_strdup("http://www.muhri.net/skipstone");
       	config.xsize = 700;
     	config.ysize = 500;
       	config.layout = 0;
     	config.mailer = g_strdup("pronto");
       	config.downloader = g_strdup("wget");
     	config.maxpopupitems = 15;
       	config.bmarktbar = 1;
	/*                  */

	config_file = fopen(file,"r");
	if (config_file == NULL) {
	     	write_config();
		return;
	}

	line = (gchar *)g_malloc(1024);

	while(fgets(line,1024,config_file) != NULL) {
		line[strlen(line)-1] = '\0';
		if (g_strncasecmp(line,"home=",5) == 0) {
			g_free(config.home);
		     	config.home = g_strdup(line+5);
			if (g_strcasecmp(config.home,"") == 0) {
				g_free(config.home);
				config.home = g_strdup("about:blank");
			}
		} else if (g_strncasecmp(line,"xsize=",6) == 0) {
			config.xsize = atoi(line+6);
		} else if (g_strncasecmp(line,"ysize=",6) == 0) {
			config.ysize = atoi(line+6);
		} else if (g_strncasecmp(line,"layout=",7) == 0) {
			config.layout = atoi(line+7);
		} else if (g_strncasecmp(line,"mailer=",7) == 0) {
		     	g_free(config.mailer);
		     	config.mailer = g_strdup(line+7);
		} else if (g_strncasecmp(line,"downloader=",11) == 0) {
		     	g_free(config.downloader);
		     	config.downloader = g_strdup(line+11);
		} else if (g_strncasecmp(line,"maxpopup=",9) == 0) {
		     	config.maxpopupitems = atoi(line+9);
		} else if (g_strncasecmp(line,"bmarktbar=",10) == 0) {
		     	config.bmarktbar = atoi(line+10);
		}
	}
	fclose(config_file);

     	g_free(line);
	g_free(file);
	return;
}



void 
write_config() 
{
	FILE *config_file;
	gchar *home;
	gchar *file;

	home = getenv("HOME");

     	file = g_strconcat(home,"/.skipstonerc",NULL);
     	config_file = fopen(file,"w");
	if (config_file == NULL) {
		printf("umm, why cant we write the config file\n");
		return;
	}

	fprintf(config_file,"home=%s\n",config.home);
	fprintf(config_file,"xsize=%d\n",config.xsize);
	fprintf(config_file,"ysize=%d\n",config.ysize);
	fprintf(config_file,"layout=%d\n",config.layout);
	fprintf(config_file,"mailer=%s\n",config.mailer);
	fprintf(config_file,"downloader=%s\n",config.downloader);	
	fprintf(config_file,"maxpopup=%d\n",config.maxpopupitems);
     	fprintf(config_file,"bmarktbar=%d\n",config.bmarktbar);	
     
     	fclose(config_file);
	g_free(file);
	return;
}


void 
read_urls() 
{
	FILE *url_file;
	gchar *file;
	gchar *line;
	gchar *url;
	gchar *home;

	home = getenv("HOME");
	file = g_strconcat(home,"/.skipstone/urls",NULL);
	url_file = fopen(file,"r");
	if (url_file == NULL) {
		printf("no urls to read\n");
		return;
	}
	line = (gchar *)g_malloc(1024);

	while(fgets(line,1024,url_file) != NULL) {
		line[strlen(line)-1] = '\0';
		url = g_strdup(line);
		combo_urls = g_list_append(combo_urls,url);
	}

	fclose(url_file);
	g_free(line);
	g_free(file);
	return;
}

	
void 
write_urls() 
{
	FILE *url_file;
	gchar *file;
	gchar *home;
       	GList *list;
     	
	home = getenv("HOME");
	file = g_strconcat(home,"/.skipstone/urls",NULL);
	url_file = fopen(file,"w");
	if (url_file == NULL) {
		printf("cant write urls, this is.. bad\n");
		return;
	}

	

	for (list = combo_urls; list ; list = list->next) {
		fprintf(url_file,"%s\n",(gchar *)(list->data));
	}
	fclose(url_file);
	g_free(file);	
	return;

}


void 
update_layout() 
{
	gint length;
     	gint i;
     	length = g_slist_length(window_count);
      	for (i = 0; i < length ; i++) {	     	
	     	Bdata *bdata = g_slist_nth_data(window_count,i);
	     	if (bdata->window !=NULL) {
	     		gtk_toolbar_set_style(GTK_TOOLBAR(bdata->toolbar),config.layout);
			gtk_widget_queue_resize(GTK_WIDGET(bdata->handlebox));
		}
	}
	     
     	return;
}


void
insert_in_combo(gchar *url, Bdata *bdata)
{
     	gint length;
	gint i;
	gint dontadd;
	gchar *url_in_glist;
	length = g_list_length(combo_urls);
	dontadd = 0;

	if (url[strlen(url)-1] == '/') {
		url[strlen(url)-1] = '\0';
	}

  	for (i = 0; i < length; i++) {
		url_in_glist = (gchar *)g_strdup(g_list_nth_data(combo_urls,i));

		if (url_in_glist[strlen(url_in_glist)-1] == '/') {
			url_in_glist[strlen(url_in_glist)-1] = '\0';
		}

		if (g_strcasecmp(url_in_glist,url) == 0 ) {
	     		dontadd = 1;
			g_free(url_in_glist);
			break;
		}
		g_free(url_in_glist);
	}
	if (!dontadd) 	{
	     
	     	if (length + 1 >  config.maxpopupitems) { /* delete the last item if its more than the configured limit */
		     	combo_urls = g_list_remove(combo_urls, g_list_nth_data(combo_urls,length-1));
		}
		combo_urls = g_list_prepend(combo_urls, url); 	
	     	gtk_combo_set_popdown_strings(GTK_COMBO(bdata->combo),combo_urls);
	     	write_urls();
	}
	return;
}


void make_window_from_popup(GtkWidget *menuitem, Bdata *bdata)
{
        make_window(bdata->link);          
	return;
}

void browse_in_window_from_popup(GtkWidget *menuitem, Bdata *bdata) 
{
	gtk_moz_embed_load_url(bdata->embed, bdata->link);
	return;
}
	    
void download_link_from_popup(GtkWidget *menuitem, Bdata *bdata) 
{


     	if (!config.downloader || !bdata->link) {
	     return;	     
	}
     
  	download_url(bdata->link);
	return;
}
     
void destroy_popup()
{

	    	gtk_widget_destroy(popupmenu);
        	popupmenu = NULL;
		return;
}

gint
menu_timeout(Bdata *bdata)
{
	gint x,y;
	GdkModifierType mask;
	mask = 0;

	gdk_window_get_pointer (bdata->window->window, &x, &y, &mask);
	g_return_val_if_fail(bdata->menu_timer !=NULL, FALSE);
	
	if (mask & GDK_BUTTON3_MASK) {
	 	if (bdata->link !=NULL && g_strcasecmp(bdata->link, "") != 0) {
             		if (popupmenu !=NULL) {
			     	destroy_popup();
			}
		     	popupmenu = get_popup_menu(bdata);
	     		gtk_menu_popup(GTK_MENU(popupmenu), NULL, NULL, NULL, NULL, GDK_BUTTON3_MASK, 1);
	     		printf("popup menu %s\n", bdata->link);
		     	g_timer_stop(bdata->menu_timer);
	     		gtk_timeout_remove(bdata->menu_timeout_id);

		}
      	} else if (mask & GDK_BUTTON2_MASK) {
		if (bdata->link !=NULL && g_strcasecmp(bdata->link, "") != 0) {
	     		make_window(bdata->link);
			g_timer_stop(bdata->menu_timer);
			gtk_timeout_remove(bdata->menu_timeout_id);
			printf("middle click %s\n", bdata->link);
	
		}
	}
	

     return TRUE;
}

void
quit_skipstone()
{
	gchar *home;
     	gchar *file;
     	home = getenv("HOME");
     	file = g_strconcat(home,"/.skipstone/running", NULL);
     	unlink(file);
     	g_free(file);
     	write_config();
	gtk_main_quit();
	gtk_exit(0);
	return;
}

void read_bookmarks() {
	FILE *bookmark_file;
	gchar *file;
	gchar *line;
	gchar *home;
	gchar **temp;

	home = getenv("HOME");
	file = g_strconcat(home,"/.skipstone/bookmarks",NULL);
	bookmark_file = fopen(file,"r");
	if (bookmark_file == NULL) {
		printf("no bookmarks to read\n");
		return;
	}
	line = (gchar *)g_malloc(1024);

	while(fgets(line,1024,bookmark_file) != NULL) {
		BookmarkData *bookmark;
		bookmark = g_new0(BookmarkData,1);

		line[strlen(line)-1] = '\0';
		if (g_strcasecmp(line,"") == 0) {
			continue;
		}
		temp = g_strsplit(line,"`",3);

		bookmark->url = g_strdup(temp[0]);
		bookmark->pos = atoi(temp[1]);
		bookmark->label = g_strdup(temp[2]);
		g_strfreev(temp);
		bookmarks = g_list_append(bookmarks,bookmark);
	}

	fclose(bookmark_file);
	g_free(line);
	g_free(file);
	return;
}

void write_bookmarks() {
	FILE *bookmark_file;
	gchar *file;
	gchar *home;
	gint i;

	home = getenv("HOME");
	file = g_strconcat(home,"/.skipstone/bookmarks",NULL);
	bookmark_file = fopen(file,"w");

	for (i = 0; i < g_list_length(bookmarks); i++) {
		BookmarkData *bmark = g_list_nth_data(bookmarks,i);
		fprintf(bookmark_file,"%s`%d`%s\n",bmark->url,bmark->pos,bmark->label);
	}

	fclose(bookmark_file);
	g_free(file);
	return;
}

void generate_bookmark_ui(Bdata *bdata) {
	GtkWidget *bookmark_add,*bookmark_edit,*sep;
	gint i;
	gint j;

	if (bdata->bookmark_menu) {
		gtk_widget_destroy(bdata->bookmark_menu);
	}

	j = g_slist_length(bdata->bookmark_toolbar_widgets);
	for (i = 0; i < j; i++) {
		gtk_widget_destroy(g_slist_nth_data(bdata->bookmark_toolbar_widgets,i));
	}
	g_slist_free(bdata->bookmark_toolbar_widgets);
	bdata->bookmark_toolbar_widgets = NULL;
	


	bdata->bookmark_menu = gtk_menu_new();
	gtk_widget_show(bdata->bookmark_menu);
	gtk_menu_item_set_submenu(GTK_MENU_ITEM(bdata->bookmark_menubar_item),bdata->bookmark_menu);

	bookmark_add = gtk_menu_item_new_with_label("Add Bookmark");
	gtk_widget_show(bookmark_add);
	gtk_signal_connect(GTK_OBJECT(bookmark_add),"activate",GTK_SIGNAL_FUNC(add_bookmark),bdata);
	gtk_menu_append(GTK_MENU(bdata->bookmark_menu),bookmark_add);

	bookmark_edit = gtk_menu_item_new_with_label("Edit Bookmarks");
	gtk_widget_show(bookmark_edit);
	gtk_signal_connect(GTK_OBJECT(bookmark_edit),"activate",GTK_SIGNAL_FUNC(edit_bookmarks),NULL);
	gtk_menu_append(GTK_MENU(bdata->bookmark_menu),bookmark_edit);

	sep = gtk_menu_item_new();
	gtk_widget_show(sep);
	gtk_menu_append(GTK_MENU(bdata->bookmark_menu), sep);

	for (i = 0; i < g_list_length(bookmarks); i++) {
		BookmarkData *bmark = g_list_nth_data(bookmarks,i);
		GtkWidget *item;

		if (bmark->pos == 0) {
			item = gtk_menu_item_new_with_label(bmark->label);
			gtk_menu_append(GTK_MENU(bdata->bookmark_menu),item);
			gtk_signal_connect(GTK_OBJECT(item),"activate",GTK_SIGNAL_FUNC(bookmark_activate),bdata);
		} else {
			item = gtk_button_new_with_label(bmark->label);
			gtk_button_set_relief(GTK_BUTTON(item),GTK_RELIEF_NONE);
 	 	   	gtk_toolbar_append_widget(GTK_TOOLBAR(bdata->bookmark_toolbar),item,bmark->label,"");
			gtk_signal_connect(GTK_OBJECT(item),"clicked",GTK_SIGNAL_FUNC(bookmark_activate),bdata);

			bdata->bookmark_toolbar_widgets = g_slist_append(bdata->bookmark_toolbar_widgets,item);
		}
		gtk_object_set_data(GTK_OBJECT(item),"bmark",bmark);
		gtk_widget_show(item);
	}

	return;
}

