/*  This file is part of lscomp.

    lscomp 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.

    lscomp 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 lsnet.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "gtk_funcs.h"

gboolean on_destroy(GtkWidget *widget, GdkEventButton *event, gpointer data){
        gtk_main_quit();
	return 0;
}

gboolean on_comp(GtkWidget *widget, GdkEventButton *event, gpointer data){
	gchar *text;
	text = malloc(sizeof(gchar)*15);
	double principle1 = atof( gtk_entry_get_text(GTK_ENTRY(  ((struct ToolTab *)data)->comp_entries[0]   )) );
	double rate1 = atof( gtk_entry_get_text(     GTK_ENTRY(  ((struct ToolTab *)data)->comp_entries[1]   )) );
	double principle2 = atof( gtk_entry_get_text(GTK_ENTRY(  ((struct ToolTab *)data)->comp_entries[2]   )) );

	rate1 = rate1 / 100;
	double times1 = (log(principle2) - log(principle1)) / log(1+rate1);
	printf("%lf\n", times1);
	(void)sprintf(text, "%lf", times1 );
	gtk_entry_set_text(GTK_ENTRY( ((struct ToolTab *)data)->comp_entries[3] ), text);
	free(text);
	//gtk_widget_show_all(GTK_WIDGET(  ((struct ToolTab *)data)->main_table  ));
	gtk_widget_show_all(GTK_WIDGET( widget ));
	return 0;
}

gboolean on_comp_s(GtkWidget *widget, GdkEventButton *event, gpointer data){
	double rate1;
	double principle1 = atof( gtk_entry_get_text(GTK_ENTRY(  ((struct ToolTab *)data)->comp_s_entries[0]   )) );
	double principle2 = principle1;
	double last;

	const char *token;
	const char *search = " ";
	gchar *text;

	//unsigned long entry_size = sizeof(  gtk_entry_get_text(GTK_ENTRY(  ((struct ToolTab *)data)->comp_s_entries[1]   ))  );
	


	//const gchar *rates = gtk_entry_get_text(GTK_ENTRY(  ((struct ToolTab *)data)->comp_s_entries[1]   ));

	unsigned long entry_size = strlen(gtk_entry_get_text(GTK_ENTRY(  ((struct ToolTab *)data)->comp_s_entries[1]   )));
	gchar *rates;
	rates = (gchar *)malloc(entry_size );
	memset( (void *)rates, '\0', entry_size );

	strcpy((char *)rates, (const char *)gtk_entry_get_text(GTK_ENTRY(  ((struct ToolTab *)data)->comp_s_entries[1]   ))  );

	printf("size: %lu\n", entry_size);
	text = malloc(sizeof(gchar)*9);

	memset( (void *)text, '\0', 9 );


	for(token = strtok((char *)rates, search); token != NULL; token = strtok(NULL, search) ){
		
		rate1 = atof(token);
		last = principle2;
		principle2 =  principle2 * ((100+rate1)/100);
		last = principle2 - last;
	}

	//last = principle2 - principle1;
	//rate1 = ((principle2 / principle1)-1) * 100;
	//if( abs(principle2) <= pow( 2, sizeof(unsigned long)*8)  ) {
		
		(void)sprintf((char *)text, "%.04lf", principle2 );
		gtk_entry_set_text(GTK_ENTRY( ((struct ToolTab *)data)->comp_s_entries[2] ), text);
		gtk_widget_show_all(GTK_WIDGET( widget ));
	//}
	//gtk_widget_show_all(GTK_WIDGET(  ((struct ToolTab *)data)->main_table  ));
	free((void *)text);
	free((void *)rates);
	return TRUE;
}

gboolean on_recoup(GtkWidget *widget, GdkEventButton *event, gpointer data){
	double percentage1 = atof( gtk_entry_get_text( GTK_ENTRY(  ((struct ToolTab *)data)->recoup_entries[0]  ) ) );
	double percentage2;
	void *text;
	text = malloc(sizeof(char)*15);
	percentage2 = 100 + percentage1;
	percentage2 = (100 / percentage2) - 1;
	percentage2 = percentage2 * 100;
	(void)sprintf(text, "%lf", percentage2 );
	gtk_entry_set_text(GTK_ENTRY( ((struct ToolTab *)data)->recoup_entries[1] ), text);
	gtk_widget_show_all(GTK_WIDGET( widget ));
	free(text);
	return 0;
}


gboolean on_file_load(GtkWidget *widget, GdkEventButton *event, gpointer data){
	GtkWidget *dialog;
	dialog = gtk_file_chooser_dialog_new ("Open File", NULL, GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
		GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL);
	if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT){
		gchar *filename;
		filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
		//open_file (filename);
		printf("filename: %s\n", filename);
		load_portfolio(filename);

		//g_free (filename);
	}
	gtk_widget_destroy (dialog);
	gtk_widget_show_all(GTK_WIDGET( widget ));
	return 0;
}

gboolean on_file_save(GtkWidget *widget, GdkEventButton *event, gpointer data){
	GtkWidget *dialog;
	dialog = gtk_file_chooser_dialog_new ("Save File", NULL, GTK_FILE_CHOOSER_ACTION_SAVE, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
		GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT, NULL);
	if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT){
		gchar *filename;
		filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
		printf("filename: %s\n", filename);
		save_portfolio(filename);
		//g_free (filename);
	}
	gtk_widget_destroy (dialog);
	gtk_widget_show_all(GTK_WIDGET( widget ));
	return 0;
}




void on_font_chng(GtkSpinButton *widget, gpointer data){
	int i;
	int j;
	Port_win.font_size = gtk_spin_button_get_value_as_int(widget);
	pango_font_description_set_size(Port_win.font_desc, Port_win.font_size * PANGO_SCALE );
	for(i=0; i<Port_win.port_rows+1; i++){
		if(i == 0){
			for(j=0; j<3; j++){
				gtk_widget_modify_font(GTK_WIDGET(Port_win.pos_labels[j]), Port_win.font_desc);
			}
		}else{
			for(j=0; j<3; j++){
				gtk_widget_modify_font(GTK_WIDGET(Port_win.pos_entries[i][j]), Port_win.font_desc);
			}
		}
		for(j=0; j<Port_win.port_cols; j++){
			gtk_widget_modify_font(GTK_WIDGET(Port_win.entries[i][j]), Port_win.font_desc);
			//gtk_widget_show(GTK_WIDGET(Port_win.entries[i][j]));
		}
	}
	//gtk_widget_error_bell(widget);
	//gtk_widget_show(GTK_WIDGET(Port_win.main_table));
	//gdk_window_beep( gtk_widget_get_root_window( gtk_widget_get_toplevel(widget) ) );
	//gdk_window_beep( gtk_widget_get_root_window( GTK_WIDGET(data) ) );
	//gdk_window_beep(GDK_WINDOW(data));
	gtk_widget_show_all(GTK_WIDGET((GtkSpinButton *)data));
	//gtk_widget_show_all(GTK_WIDGET(((struct MainWindow *)data)->window));
}

void on_row_chng(GtkSpinButton *widget, gpointer data){
	//struct PortTab *ptr = data;
	Port_win.port_rows = gtk_spin_button_get_value_as_int(widget);
	//Port_win.port_cols = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(widget));
	printf("rows: %d\n", Port_win.port_rows );
	port_adj_row();
	gtk_widget_show_all(GTK_WIDGET( (GtkSpinButton *)data ) );
}
void on_col_chng(GtkSpinButton *widget, gpointer data){
	//struct PortTab *ptr = data;
	//GTK_SPIN_BUTTON(
	Port_win.port_cols = gtk_spin_button_get_value_as_int(widget);
	//Port_win.port_rows = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(widget));
	printf("col: %d\n", Port_win.port_cols );
	port_adj_col();
	gtk_widget_show_all(GTK_WIDGET((GtkSpinButton *)data));
}
//int last_rows = 4;
//int last_cols = 10;

void on_commission_chng(GtkSpinButton *widget, gpointer data){
	//Port_win.commission = gtk_spin_button_get_value_as_double(widget);
	//Port_win.commission  = gtk_spin_button_get_value( (GtkSpinButton *)(((struct PERF_Cur *)data)->gpu_b) );
	Port_win.commission = gtk_spin_button_get_value(GTK_SPIN_BUTTON(Port_bt.button4));
	gtk_widget_show_all(GTK_WIDGET((GtkSpinButton *)data));
}

void port_adj_row(void){
	//int last_rows = 4;
	int i = 0;
	int j = 0;

	int diff = 0;

	//struct PortTab *ptr = Port_win;
	//add/remove new ticker rows

	//printf("TEST: r, %d c, %d\n", Port_win.port_rows, Port_win.port_cols);
	//for(i=0; i<port_cols; i++){
	
	//if(Port_win.port_rows == 0){
	//	Port_win.last_rows = Port_win.port_rows;
	//	return;
	//}

	if(Port_win.port_rows < Port_win.last_rows){
		
		while(Port_win.port_rows < Port_win.last_rows){


		//gtk_table_resize(GTK_TABLE(Port_win.pos_table), Port_win.last_rows+1, 3);
		//gtk_table_resize(GTK_TABLE(Port_win.out_table), Port_win.last_rows+1, Port_win.port_cols);

		//for(diff=0; diff<Port_win.last_rows-Port_win.port_rows; diff++){
		
			for(i=0; i<3; i++){
				gtk_widget_destroy(GTK_WIDGET(Port_win.pos_entries[Port_win.last_rows][i]) );
			}
			for(i=0; i<Port_win.port_cols; i++){
				gtk_widget_destroy(GTK_WIDGET(Port_win.entries[Port_win.last_rows][i]) );
			}
			
			gtk_table_resize(GTK_TABLE(Port_win.pos_table), Port_win.last_rows, 3);
			gtk_table_resize(GTK_TABLE(Port_win.out_table), Port_win.last_rows, Port_win.port_cols);

			Port_win.last_rows--;
		}
		//Port_win.port_rows -= diff;
		//gtk_table_resize(GTK_TABLE(Port_win.pos_table), Port_win.port_rows, 3);
		//gtk_table_resize(GTK_TABLE(Port_win.out_table), Port_win.port_rows, Port_win.port_cols);
		
		//Port_win.last_rows = Port_win.port_rows;
		return;
		
	}


	if(Port_win.port_rows > Port_win.last_rows){
		
		//diff = Port_win.port_rows-Port_win.last_rows;

		gtk_table_resize(GTK_TABLE(Port_win.pos_table), Port_win.port_rows+1, 3);
		gtk_table_resize(GTK_TABLE(Port_win.out_table), Port_win.port_rows+1, Port_win.port_cols);

		Port_win.entries = realloc(Port_win.entries, sizeof(GtkWidget ***) * (Port_win.port_rows+1) );
		Port_win.pos_entries = realloc(Port_win.pos_entries, sizeof(GtkWidget ***) * (Port_win.port_rows+1) );

		i=Port_win.last_rows+1;

		for(diff=0; diff<Port_win.port_rows-Port_win.last_rows; diff++){
			//i=Port_win.port_rows;
			//for(i=last_rows-1; i<Port_win.port_rows; i++){
			Port_win.entries[i+diff] = malloc(sizeof(GtkWidget **) * Port_win.port_cols );
			Port_win.pos_entries[i+diff] = malloc(sizeof(GtkWidget **) * 3 );
			for(j=0; j<3; j++){
				Port_win.pos_entries[i+diff][j] = gtk_entry_new();
				gtk_widget_modify_font(Port_win.pos_entries[i+diff][j], Port_win.font_desc);
				gtk_entry_set_width_chars(GTK_ENTRY(Port_win.pos_entries[i+diff][j]), 14);
				gtk_table_attach(GTK_TABLE(Port_win.pos_table), Port_win.pos_entries[i+diff][j], j, j+1, i+diff, i+diff+1,
					GTK_EXPAND|GTK_FILL, 0, GTK_EXPAND|GTK_FILL, 0);
			}
			for(j=0; j<Port_win.port_cols; j++){
				Port_win.entries[i+diff][j] = gtk_entry_new();
				gtk_widget_modify_font(Port_win.entries[i+diff][j], Port_win.font_desc);
				gtk_entry_set_width_chars(GTK_ENTRY(Port_win.entries[i+diff][j]), 14);
				gtk_table_attach(GTK_TABLE(Port_win.out_table), Port_win.entries[i+diff][j], j, j+1, i+diff, i+diff+1, 
					GTK_EXPAND|GTK_FILL, 0, GTK_EXPAND|GTK_FILL, 0);
			}
			//Port_win.port_rows++;
		}
		//Port_win.port_rows
		
	}
	//gtk_table_resize(GTK_TABLE(Port_win.table), Port_win.port_rows, Port_win.port_cols);
	//for(i=0; i<port_rows; i++){	
	//	Port_win.entries[i] = realloc(Port_win.entries[i], sizeof(GtkWidget **) * port_cols);
	//}
	//gtk_widget_show(GTK_WIDGET(Port_win.table));
	Port_win.last_rows = Port_win.port_rows;
}

void port_adj_col(void){
	//int last_cols = 10;
	int i = 0;
	int j = 0;
	
	//add/remove more colums to ticker rows
        if(Port_win.port_cols < Port_win.last_cols){
                for(i=0; i<Port_win.port_rows+1; i++){

                        for(j=Port_win.port_cols; j<Port_win.last_cols; j++){
                                gtk_widget_destroy(GTK_WIDGET(Port_win.entries[i][j]) );
				//free(Port_win.entries[i][j]);
                        }
                }
		
		//gtk_table_resize(GTK_TABLE(Port_win.pos_table), Port_win.port_rows, Port_win.port_cols);
		gtk_table_resize(GTK_TABLE(Port_win.out_table), Port_win.port_rows, Port_win.port_cols);
        }


	//Port_win.entries = realloc(Port_win.entries, sizeof(GtkWidget *) * port_rows * port_cols);
	//for(i=0; i<Port_win.port_rows; i++){
	//	Port_win.entries[i] = realloc(Port_win.entries[i], sizeof(GtkWidget **) * Port_win.port_cols);
	//}
	if(Port_win.port_cols > Port_win.last_cols){
		//gtk_table_resize(GTK_TABLE(Port_win.pos_table), Port_win.port_rows, Port_win.port_cols);
		gtk_table_resize(GTK_TABLE(Port_win.out_table), Port_win.port_rows+1, Port_win.port_cols);
		for(i=0; i<Port_win.port_rows+1; i++){
			Port_win.entries[i] = realloc(Port_win.entries[i], sizeof(GtkWidget **) * Port_win.port_cols);
			//for(j=last_cols-1; j<Port_win.port_cols; j++){
//			j=Port_win.port_cols-1;
			for(j=Port_win.last_cols; j<Port_win.port_cols; j++){
				Port_win.entries[i][j] = gtk_entry_new();
				gtk_widget_modify_font(Port_win.entries[i][j], Port_win.font_desc);
				gtk_entry_set_width_chars(GTK_ENTRY(Port_win.entries[i][j]), 14);
				gtk_table_attach(GTK_TABLE(Port_win.out_table), Port_win.entries[i][j], j, j+1, i, i+1, 
					GTK_EXPAND|GTK_FILL, 0, GTK_EXPAND|GTK_FILL, 0);
			}
		}
		//last_cols = Port_win.port_cols;
	}
	//gtk_table_resize(GTK_TABLE(Port_win.table), Port_win.port_rows, Port_win.port_cols);
	//gtk_widget_show(GTK_WIDGET(Port_win.table));
	Port_win.last_cols = Port_win.port_cols;
}

gboolean on_calculate(GtkWidget *widget, GdkEventButton *event, gpointer data){
	gchar *text;
	text = malloc(sizeof(gchar)*15);
	double shares;
	double price;
	double commission;
	double *changes;
	changes = malloc(sizeof(double)*Port_win.port_cols);
	int i;
	int j;
	//guint16 entry_len = 0;
	int empty = 0;
	// Port_bt.spin_adj4
	//commission = gtk_spin_button_get_value( (GtkSpinButton *)(((struct ButtonTable *)Port_bt)->spin_adj4) );

	//commission = gtk_spin_button_get_value(GTK_SPIN_BUTTON(Port_bt.button4));
	commission = Port_win.commission;

	//commission = atof( gtk_entry_get_text(GTK_ENTRY(Port_win.commission)) );

	for(j=0; j<Port_win.port_cols; j++){
		price = atof( gtk_entry_get_text(GTK_ENTRY(Port_win.entries[0][j])) );

		if(price == price && price != 0){
			changes[j] = price;
		}else{
			changes[j] = 0;
			memset((void *)text, '\0', 15 );
			(void)sprintf(text, "%d", 0 );
			gtk_entry_set_text(GTK_ENTRY(Port_win.entries[0][j]), text);
		}
	}
	for(i=1; i<Port_win.port_rows+1; i++){
		if(gtk_entry_get_text_length(GTK_ENTRY(Port_win.pos_entries[i][1])) == 0){
			empty = 1;
		}
		if(gtk_entry_get_text_length(GTK_ENTRY(Port_win.pos_entries[i][1])) == 0){
			empty = 1;
		}
		if(!empty){
	 		shares = atof( gtk_entry_get_text(GTK_ENTRY(Port_win.pos_entries[i][1])) );
			price  = atof( gtk_entry_get_text(GTK_ENTRY(Port_win.pos_entries[i][2])) );

			for(j=0; j<Port_win.port_cols; j++){
				(void)sprintf(text, "%lf", (shares*price+changes[j]+commission)/shares );
				gtk_entry_set_text(GTK_ENTRY(Port_win.entries[i][j]), text);
			}
		}
		empty = 0;
	}

	gtk_widget_show_all(GTK_WIDGET(data));
	free(changes);
	free(text);
	return 0;
}

void load_portfolio(gchar *filename){
	FILE* fp;
	gchar linestring[25*9];
	int i=0;
	int j;
	const char *token;
	const char *search = " ";
	int cols = 0;
	int rows = 0;

	//ensure the correct number of cols/rows
	memset ((void*) linestring, '\0', sizeof (linestring));
	if( ( fp = fopen(filename, "r" ) ) == NULL ) {
		fprintf( stderr, "Error opening %s\n", filename );
		return;
	}
	while( fgets(linestring, sizeof(linestring), fp) != NULL){
		if(rows == 0){
			//count cols
			token = strtok(linestring, search);
			while(token != NULL){
				token = strtok(NULL, search);
				cols++;
			}
			cols -= 3;
		}
		rows++;
		
	}
	rows -= 1;
	printf("rows: %d cols: %d\n", rows, cols);	
	fclose(fp);

	gtk_spin_button_set_value(GTK_SPIN_BUTTON(Port_bt.button1), (gdouble)rows);

	//Port_win.last_cols = Port_win.port_cols;
	//Port_win.last_rows = Port_win.port_rows;
	Port_win.port_rows = rows;
	Port_win.port_cols = cols;

	//Port_win.port_cols = Port_win.last_cols;

	port_adj_row();

	gtk_spin_button_set_value(GTK_SPIN_BUTTON(Port_bt.button2), (gdouble)cols);
	//Port_win.port_cols = cols;

	port_adj_col();


	memset ((void*) linestring, '\0', 25*9);
	if( ( fp = fopen(filename, "r" ) ) == NULL ) {
		fprintf( stderr, "Error opening %s\n", filename );
		return;
	}
	while( fgets(linestring, sizeof(linestring), fp) != NULL){
		linestring[strlen(linestring)-1] = '\0';

		token = strtok(linestring, search);
		//ignore first 3 "Ticker Shares Price "
		if(i==0){
			token = strtok(NULL, search);
			token = strtok(NULL, search);
			token = strtok(NULL, search);
		}else{
			//get pos_entries
			for(j=0; j<3; j++){
				gtk_entry_set_text(GTK_ENTRY(Port_win.pos_entries[i][j]), token);
				token = strtok(NULL, search);
			}
		}
		//get entries
		for(j=0; j<Port_win.port_cols; j++){
			
			gtk_entry_set_text(GTK_ENTRY(Port_win.entries[i][j]), token);
			token = strtok(NULL, search);
		}	
		i++;
		//memset ((void*) linestring, '\0', sizeof (linestring));
	}
	fclose(fp);
	//clear any excess feilds
	//while(i < Port_win.port_rows+1){
		
	//}


}

void save_portfolio(gchar *filename){
	FILE* fp;
	gchar linestring[25*9];
	int i;
	int j;
	int k = 0;
	int all_space = 0;
	memset ((void*) linestring, '\0', sizeof (linestring));
	strcpy(linestring, "Ticker Shares Price ");	

	if ( (fp = fopen(filename, "w")) ){
		for(i=0; i<Port_win.port_rows+1; i++){
			for(j=0; j<3; j++){
				if(i != 0){
					strcat(linestring, gtk_entry_get_text(GTK_ENTRY(Port_win.pos_entries[i][j])) );
					strcat(linestring, " ");
					
				}
				//all_space = 1;
				//for(k=0; linestring[k] != '\0'; k++){
				//	if(linestring[k] != ' ')
				//		all_space = 0;
				//}
				//if
			}
			if(i != 0){
				for(k=0; linestring[k] != '\0'; k++){
					if(linestring[k] != ' ')
						all_space = 0;
				}
			}
			if(!all_space){
				for(j=0; j<Port_win.port_cols; j++){
					strcat(linestring, gtk_entry_get_text(GTK_ENTRY(Port_win.entries[i][j])) );
					if(j != Port_win.port_cols-1){
						strcat(linestring, " ");
					}
				}

				fprintf(fp, "%s\n", linestring );

			}
			all_space = 1;
			memset ((void*) linestring, '\0', 25*9);
		}

	}
	//g_free(linestring);
	fclose(fp);
}
