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


#include "skipstone.h"
#include <time.h>

static void regular_cb(GtkWidget *button, GtkWidget *window);
static void new_win_cb(GtkWidget *button, GtkWidget *window);

time_t start_time=0;
extern GSList *window_count;
extern GList *combo_urls;
extern gchar *app_path;
extern gchar *home;
extern ConfigData config;

void save_crash_state(void) {
	SkipStone *skipstone = NULL;
	GSList *l;
	gchar *path;
	gchar *url;
	FILE *url_file;
#ifdef WebKit
   WebKitWebFrame *frame;
#endif   
     	D_ENTER;
     
	g_print(_("Creating a crash recovery file\n"));

	path = g_strconcat(home,"/.skipstone/crash_data",NULL);
	url_file = fopen(path,"w");
	for (l = window_count; l ; l = l->next) {
		skipstone = l->data;
#ifndef WebKit	   
		url = gtk_moz_embed_get_location(skipstone->embed);
#else	   
	        frame = webkit_web_view_get_main_frame(skipstone->embed);
	        url = webkit_web_frame_get_uri(frame);
#endif	   
		if ((url != NULL) && (strcmp(url,"") != 0))
			fprintf(url_file,"%s\n",url);
#ifndef WebKit		
		if (url != NULL) g_free(url);
#endif	   
	}
	fclose(url_file);
	g_free(path);
     	D_RETURN;
}

void crash_list_selection_made(GtkWidget *clist,gint row,gint column,GdkEventButton *event,GtkWidget *window) {
	gchar *text;
	gchar *duped;
     	D_ENTER;
	gtk_clist_get_text(GTK_CLIST(clist), row, column, &text);
	g_print(_("recovering %s\n"),text);
     	duped = g_strdup(text);
     	gtk_clist_remove(GTK_CLIST(clist),row);
     	make_window(duped);
      	g_free(duped);
	if (GTK_CLIST(clist)->rows == 0) {
		gtk_widget_destroy(window);
	}

	D_RETURN;
}

gint check_crash_file(void) {
	FILE *url_file;
	gchar *file;
	gchar *url = NULL;
	gchar *line;
	GtkWidget *vbox, *window,*scrolled_window,*clist,*label,*btnbox,*new_win,*regular,*quit;
	gint retVal = 0;
	
     	D_ENTER;
     	
     	time(&start_time); /* this remembers the time of last start to prevent fast crashes/restarts */     
	
     	file = g_strconcat(home,"/.skipstone/crash_data",NULL);
     
	url_file = fopen(file,"r");
	if (url_file != NULL) {
		window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	        skipstone_window_set_icon(window);
		gtk_window_set_title(GTK_WINDOW(window), _("Crash Recovery"));
		gtk_window_set_default_size(GTK_WINDOW(window), 600, 0);
				
		vbox = gtk_vbox_new(0,0);
		gtk_container_add(GTK_CONTAINER(window), vbox);
		
		label = gtk_label_new (_("It appears that skipstone has crashed.\n Click on one of the saved urls below to open it in a new window"));
		gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_LEFT);
		gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, FALSE, 0);
	
		scrolled_window = gtk_scrolled_window_new(NULL, NULL);
		gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled_window), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
	     

	
		clist = gtk_clist_new(1);

	
		line = (gchar *)g_malloc(1024);

		while(fgets(line,1024,url_file) != NULL) {
			gchar *clist_entry[0];
			line[strlen(line)-1] = '\0';
			g_strchomp(line);
		     	clist_entry[0] = g_strdup(line);
			gtk_clist_append(GTK_CLIST(clist),clist_entry);
			retVal++;
		}

		fclose(url_file);
		unlink(file);
		g_free(url);
		g_free(line);
		/* It really sucks to have an empty crash recovery thing pop up. This insures that it doesn't happen */
		if(retVal != 0){
			
		     	g_signal_connect(G_OBJECT(clist),"select_row",G_CALLBACK(crash_list_selection_made),window); 
			gtk_container_add(GTK_CONTAINER(scrolled_window), clist);
			gtk_box_pack_start(GTK_BOX(vbox), scrolled_window, TRUE, TRUE, 0);		
			
			btnbox = gtk_hbox_new(0,0);
			gtk_box_pack_start(GTK_BOX(vbox), btnbox, FALSE, FALSE, 0);
			new_win = gtk_button_new_with_label(_("Supply another URL"));
			regular = gtk_button_new_with_label(_("Just start normally"));
			quit = gtk_button_new_from_stock(GTK_STOCK_QUIT);
			
			g_signal_connect(G_OBJECT(new_win), "clicked", G_CALLBACK(new_win_cb), window);
			g_signal_connect(G_OBJECT(regular), "clicked", G_CALLBACK(regular_cb), window);
			g_signal_connect(G_OBJECT(quit), "clicked", G_CALLBACK(quit_skipstone), NULL);
			
			gtk_box_pack_start(GTK_BOX(btnbox), new_win, TRUE, TRUE, 0);
			gtk_box_pack_start(GTK_BOX(btnbox), regular, TRUE, TRUE, 0);
			gtk_box_pack_start(GTK_BOX(btnbox), quit, TRUE, TRUE, 0);
			gtk_widget_show_all(window);
		
		} else if (retVal==0) {
		     	gtk_widget_destroy(window);
		}	       
	}
	g_free(file);
	D_RETURN_ ( retVal );
}


void handle_segv_signal(int sig){
	gchar *run;
	time_t current_time=0;
     	D_ENTER;
	save_crash_state();
	/* make the app run in the background */
	time(&current_time);
	if(current_time-start_time > 10){ /* Is that a reasonable delay between start -> crash? */
	   gchar *file;
	   file = g_strconcat(home,"/.skipstone/running", NULL);

	   unlink(file);
	   g_free(file);
     	/* sometimes NULL values sneak up when getting segvs from mozilla 
	 * so do some checks before writing the config file */
	   if (config.home != NULL && config.xsize && config.ysize && config.mailer != NULL) /* those are enough */            
	     write_skipstone_config();
	   write_skipstone_plugin_config();
#ifndef WebKit
	   mozilla_save_prefs ();
#endif
	   run = g_strdup_printf("%s &",app_path);
	   system(run);
	   g_free(run);
	} else {
	 	g_print(_("It looks like Skipstone is respawning too fast.\nCheck your moz-embed, it could be faulty.\n"));
	}	
//	quit_skipstone();
	exit(0);
     	D_RETURN;
}


static void new_win_cb(GtkWidget *button, GtkWidget *window)
{
     	D_ENTER;
     	gtk_widget_destroy(window);
     	open_in_new_window(NULL,NULL);
       	D_RETURN;
}

static void regular_cb(GtkWidget *button, GtkWidget *window)
{
     	D_ENTER;
     	gtk_widget_destroy(window);
     	make_window(NULL);
	D_RETURN;
}
