#     G-Tablix, graphical user interface for Tablix
#     Copyright (C) 2004,2005 Bostjan Spetic
# 
#     This program 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 2 of the License, or
#     (at your option) any later version.
# 
#     This program 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 this program; if not, write to the Free Software
#     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# author: Bostjan Spetic, igzebedze@cyberpipe.org
# module for resulting timetable preview
# 19.12.2004, 30.1.2005, 8.3.2005

use strict;

my %cells;	# currently displayed time table
my %defined_entries;
my %uid_entries;
my %grades;
my %periods;
my %days;
# local $defined_tt_entries,$uid_tt_entries

sub clear_ttview {
	%cells = ();
	%defined_entries = ();
	%uid_entries = ();
	%grades = ();
	%periods = ();
	%days = ();
}

sub on_button_export_tt_clicked { 
	my $filename = &get_filename("save",gettext("Export timetable"));
	my $me = &export_tt($filename); 
	if ($me) { &write_to_statusbar(gettext("Timetable sucesfully saved."));		
	} else { &write_to_statusbar(gettext("Saving timetable failed."));		
	}
}

sub export_tt {
	my ($filename) = @_;
	my $form = &get_form;
	my $tablix = &get_external('tablix');	
		$tablix =~ /\/(tablix.*)$/;
		$tablix = $1;
	my $how = $form->get_widget('combo_entry_tt_exports')->get_text();
	my $input = &get_defd;
	if ($filename ne "cancel") {
		if (-e $filename) { system("mv $filename $filename.bak"); }
# moznosti so: individual, all individuals, combined, styled combined, csv combined
		if ($how eq gettext("Individual")) {
			my $me = $form->get_widget('treeview_ttview_all'); 
			(my $path, my $col) = $me->get_cursor(); 
			if ((defined $path) and ($path ne "")) {
	 			my $iter = $me->get_model->get_iter($path);
	 			my $who = &clean_who($me->get_model->get($iter,0)); 
	 	  		open (WHAT,">$filename");
	 	  		print WHAT &html_result($who);
	 	  		close WHAT;			
			}
		} elsif ($how eq gettext("All Individuals")) {
			&save_all_tt($filename);
		} elsif ($how eq gettext("Combined")) {
	  		system ($tablix."_output -d 0 -o $filename html $input");	
		} elsif ($how eq gettext("Styled Combined")) {
	  		my $cssheet = &get_doc.'/style.css';
			system ($tablix."_output -d 0 -s $cssheet -o $filename htmlcss $input");			
		} elsif ($how eq gettext("CSV Combined")) {
	  		system ($tablix."_output -d 0 -o $filename csv $input");			
		} elsif ($how eq gettext("Result XML file")) {
			system ("cp $input $filename");
		} else {
			return 0;
		}
	} else {
		return 0;
	}
	return 1;
}
sub clean_who {
	my ($who) = @_;
	my $type1 = gettext("Teacher").': ';
	my $type2 = gettext("Class").': ';
	my $type3 = gettext("Room").': ';
 	$who =~ s/$type1//;
	$who =~ s/$type2//;
	$who =~ s/$type3//;	
	return $who;
}
sub save_all_tt {
	my ($filename) = @_;
	my ($form) = &get_form;
	my $defd = $defined_entries{&get_defd};	#defined_entries for the current file
	 if ($defd) {
	 	my %list;
	 	if ($filename ne "cancel") {
	  	 	while ((my $key, my $value) = each %{$defd}) {
	  	 		my $teach = (split/\|\|/,$value)[2];
	  	 		my $class = (split/\|\|/,$value)[0];	 
	  	 		my $room = (split/\|\|/,$key)[0];
	  			$list{gettext("Teacher").":$teach"} = "";
	  	 		$list{gettext("Class").":$class"} = "";
	  			$list{gettext("Room").":$room"} = "";
	  	 	}	
	 	# entries in %def... are multiple...
	 		my @who = sort(keys(%list));		
	 		foreach my $who (@who) {
	 			my $what = (split/:/,$who)[0];
	 			my $how = (split/:/,$who)[1];
	 				if (-e "$filename-$what-$how.html") {
	 					system("mv $filename/$what-$how.html .$filename-$what-$how.html.bak"); 
	 				}
	 				open (WHAT,">$filename-$what-$how.html");
	 				print WHAT &html_result($how,$filename);
	 				close WHAT;	
	 		}
	 	}
	 }
}

sub html_result {
	my ($what,$filename) = @_;
	if ((defined $what) and ($what ne "")) {
	my ($form) = &get_form;	
	my $oldtable = $form->get_widget('viewport-result')->get_child;
	my ($days,$periods) = (($oldtable->get('n-columns') - 1),($oldtable->get('n-rows') - 1));#&get_dim($filename);
	my $output = "<html>\n<head><title>".gettext("Timetable for").
					" $what</title></head>\n<body>\n<table border=1>\n<tr>";
# title row
 	for (my $i = 0; $i <= $days; $i++) {
 		if ($i == 0) {
 			$output = $output."<td align=center><b>".gettext("Period")."</b></td>";	
 		} else {
 			$output = $output."<td align=center><b>".gettext("Day")."$i</b></td>";	
 		}
 	}
 	$output = $output."</tr>\n";
	for (my $i = 0; $i < $periods; $i++) {
		$output = $output."<tr><td align=center>".($i + 1)."</td>";
		for (my $k = 0; $k < $days; $k++) {
			my $cell = $cells{$k.'_'.$i};
			my $text = $cell->get_buffer;
				$text = $text->get_text($text->get_start_iter,
												$text->get_end_iter,
												0);
				$text =~ s/\n/<br>/g;
			$output = $output."<td align=center>".$text."</td>";
		}
		$output = $output."</tr>\n";
	}
# body
#	$output =~ s/\d*-\d*/<p><br><\/p>/g; 
	return $output;
	}
}

sub on_combo_entry_tt_result_changed {
	my $what = $_[0]->get_text;
}
sub get_dim {
	my ($filename) = @_;
	my $form = &get_form;
	my $days = $days{$filename};
	my $periods = $periods{$filename};
	if (!$days) { $days = $form->get_widget('entry_days')->get_text; }
	if (!$periods) { $periods = $form->get_widget('entry_periods')->get_text; }
	return ($days,$periods);
}
sub on_button_change_tt_clicked {
	my (undef,$what) = @_;
	my ($form) = &get_form;
	my $filename = &get_defd;

	my ($days,$periods) = &get_dim($filename);
#	my @days = ("periods","monday","tuesday","wednesday","thursday","friday","saturday","sunday");

# re-initialize the timeTable
#	$form->get_widget('viewport-result')->freeze_child_notify;
	my $oldtable = $form->get_widget('viewport-result')->get_child;
# if the old table is of wrong size
	if ((defined $oldtable)) {
		if (($oldtable->get('n-columns') ne ($days + 1)) or ($oldtable->get('n-rows') ne ($periods + 1))) {
		$form->get_widget('viewport-result')->remove($oldtable); 
		undef $oldtable;
		}
	}
# recreate if necesary
	if (!defined $oldtable) {
	 	my $ttable = new Gtk2::Table(($periods + 1),($days + 1),0);
	 	$form->get_widget('viewport-result')->add($ttable);
	 	$ttable->set_row_spacings(2);
	 	$ttable->set_col_spacings(2);
	 	$ttable->set_name("ttable");
	 	$ttable->set('homogeneous' => 1);
		$ttable->show; 
	 
	 # title row
	 	for (my $i = 1; $i <= $days; $i++) {
	 		my $cell = new Gtk2::Label();
	 		$ttable->attach_defaults($cell,$i,($i + 1),0,1);
	 		$cell->set_use_markup(1);
	 		$cell->set_markup("<b>".gettext("Day")."$i</b>");	
	 		$cell->show;
	 	}
	 # periods column
	 	for (my $i = 1; $i <= $periods; $i++) {
	 		my $cell = new Gtk2::Label();
	 		$ttable->attach_defaults($cell,0,1,$i,($i + 1));
	 		$cell->set_use_markup(1);
	 		$cell->set_markup("<b>$i.</b>");	
	 		$cell->show;
	 	# all other cells 
	 		for (my $k = 1; $k <= $days; $k++) {
	 	 		my $text = new Gtk2::TextBuffer();
	 			my $cell = new Gtk2::TextView();   
	 			my $name = ($k - 1).'_'.($i - 1);		# celice vsebine tabele imajo imena od 0 dalje...
	 			$cell->set_buffer($text);					# ... kar je zelo prikladno za tablixov output
	 			$cell->set_justification('center');
	  			$cell->set_name($name);
	 			$ttable->attach_defaults($cell,$k,($k + 1),$i,($i + 1));			
	 			$cell->show;
	 			$cells{$name} = $cell;
	 		}
		}
# or simply clear the cells
	} else {
		while ((my $name, my $cell) = each %cells) {
			my $text = $cell->get_buffer;
	 		$text->set_text("");				
		}
	}
# body
#$uid_tt_entries{$i} = "$class||$title||$teacher";
#$defined_tt_entries{"$room||$period||$day"} = "$class||$title||$teacher";	
if ($filename and (defined $what)) {	
	my $defd = $defined_entries{$filename};
	$what = &clean_who($what);

	while ((my $value, my $key) = each %{$defd}) {
		my $teach = (split/\|\|/,$key)[2];
		my $class = (split/\|\|/,$key)[0];
		my $title = (split/\|\|/,$key)[1];
		my $room = (split/\|\|/,$value)[0];
		my $period = (split/\|\|/,$value)[1];
		my $day = (split/\|\|/,$value)[2];
		if (($class eq $what) or ($teach eq $what) or ($room eq $what)) {
			my $text = $cells{$day.'_'.$period}->get_buffer;
	 		$text->set_text("$class\n$teach\n$title\n$room");	
		} 
	}
#	$form->get_widget('viewport-result')->thaw_child_notify;
}
}
sub on_button_tt_print_clicked {
	my $tempdir = &get_temp;
	my $yes = &export_tt("$tempdir/output.html");
	if ($yes == 1) {
		my @files = readpipe ("ls $tempdir/output*.html");
		foreach my $file (@files) {
			chop ($file);
			system ("cat $file | html2ps | lp");
		}
		#system ("more $tempdir/output | html2ps | lp");
	} else {
		&check(gettext("Error at exporting..."),'error',1);
	}
}
sub on_treeview_ttview_all_cursor_changed {
	my ($me) = @_;
	(my $path, my $col) = $me->get_cursor(); 
	my $iter = $me->get_model->get_iter($path);
	my $what = $me->get_model->get($iter,0);	
	&on_button_change_tt_clicked(undef,$what);
}
sub on_treeview_ttview_files_cursor_changed {	# load results from another file
	my ($me) = @_;
	my ($form) = &get_form;
	(my $path, my $col) = $me->get_cursor(); 
	my $iter = $me->get_model->get_iter($path);
	my $filename = $me->get_model->get($iter,0);	
	
# remember current selection
	my $tt_all = $form->get_widget('treeview_ttview_all');
	my $what = ($tt_all->get_cursor)[0];
	if (defined $what) {
		$what = $tt_all->get_model->get_iter($what);
		$what = $tt_all->get_model->get($what,0);
	} 
# rebuild ttview_all
	$tt_all->get_model->clear;
	my %list;	
	while ((my $value, my $key) = each %{$defined_entries{$filename}}) {     
		my $teach = (split/\|\|/,$key)[2];
		my $class = (split/\|\|/,$key)[0];
		my $title = (split/\|\|/,$key)[1];
		my $room = (split/\|\|/,$value)[0];
		my $period = (split/\|\|/,$value)[1];
		my $day = (split/\|\|/,$value)[2];
		$list{gettext("Room").": $room"}  = "";
		$list{gettext("Teacher").": $teach"} = "";
		$list{gettext("Class").": $class"} = "";
	}
	@{$form->get_widget("treeview_ttview_all")->{data}} = (sort(keys(%list)));

	$form->get_widget('label-chromo')->set_text($grades{$filename});		
	if (defined $what) {
		$iter = &find_clist_row('ttview_all',$what);
		if ($iter ne 'new') { 
			$iter = $tt_all->get_model->get_iter_from_string($iter);
			$tt_all->set_cursor($tt_all->get_model->get_path($iter),undef,0); 
		}
	}
	&on_button_change_tt_clicked(undef,$what);
}
sub load_result {
	my ($filename) = @_;
	my ($form) = &get_form;
	my $tt = $form->get_widget('treeview_ttview_files')->get_model;
	
	my %tu; my %td; my $grade; my $days, my $periods;
	(	$uid_entries{$filename},
		$defined_entries{$filename},
		$grade,$days,$periods
	) = &xml_result($filename,\%tu,\%td);
	
	$grades{$filename} = $grade;
	$periods{$filename} = $periods;
	$days{$filename} = $days;
	
	my @fixs = keys(%td);
	if ($#fixs != -1) { 
		my $row = $tt->append; 
		$tt->set($row,0,$filename);	
	}
}
sub get_defd {
	my ($form) = &get_form;
	my $files = $form->get_widget('treeview_ttview_files');
	(my $path, my $col) = $files->get_cursor(); 
	if (defined $path) {
		my $iter = $files->get_model->get_iter($path);
		my $file = $files->get_model->get($iter,0);	
		$file;
	} else { return 0; }
}
sub clear_results {
	my $form = &get_form;
	$form->get_widget('treeview_ttview_all')->get_model->clear;
	$form->get_widget('treeview_ttview_files')->get_model->clear;
}
sub on_button_ttview_import_clicked {
	my @filename = &get_filename('open',gettext("Select result file"),undef,1);
	foreach my $filename (@filename) {
		if ($filename ne 'cancel') { &load_result($filename); }
	}
}
sub on_treeview_ttview_files_key_release_event { 
	my ($where, $now) = @_;
	if ($now->keyval == 65535) {
		&ttview_file_remove;
	}
}
sub on_treeview_ttview_files_button_press_event { 
	my ($where, $now) = @_;
	if (($_[1]->button == 3)) { 
		&draw_context_menu ($where, $now,"ttview_files"); 
	}
}
sub on_treeview_ttview_all_button_press_event { 
	my ($where, $now) = @_;
	if (($_[1]->button == 3)) { 
		&draw_context_menu ($where, $now,"ttview_all"); 
	}
}
sub ttview_file_remove {
	my $form = &get_form;
	my $tt = $form->get_widget('treeview_ttview_files');
	my ($path,$col) = $tt->get_cursor;
	if (defined $path) {
		my $iter = $tt->get_model->get_iter($path);
		$tt->get_model->remove($iter);
		$form->get_widget('treeview_ttview_all')->get_model->clear;
		&on_button_change_tt_clicked;
		$form->get_widget('label-chromo')->set_text('');		
	}
}
sub on_importresult_activate { &on_button_ttview_import_clicked; }
sub on_exportresult_activate { &on_button_export_tt_clicked; }

return 1;
