#     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 gui helper functions
# 29.1.2005

use strict;


sub select_row {
	my $what = $_[0];
	my $form = &get_form;
#	my $modules = &get_modules;
	my $rests_active = $form->get_widget('toggletoolbutton_options')->get_active;
	&on_button_toolbar_cancel_clicked;	
	if ($what eq "tt") {
		my $tw = $form->get_widget('treeview_tt');
		(my $path, my $col) = $tw->get_cursor(); 
		if (defined $path) {
	 		my $iter = $tw->get_model->get_iter($path);
	 		my @vals = $tw->get_model->get($iter,0,1,2,3,4,5,6,7,8);
	 		for (my $i = 0; $i <= $#vals; $i++) { if (!defined $vals[$i]) { $vals[$i] = ""; } }
	 		$form->get_widget('combo_entry_tt_class')->set_text($vals[0]);	
	 		$form->get_widget('combo_entry_tt_subject')->set_text($vals[1]);
	 		$form->get_widget('combo_entry_tt_teacher')->set_text($vals[2]);
	 		$form->get_widget('combo_entry_tt_classroom')->set_text($vals[4]);
	 		$form->get_widget('entry_tt_perweek')->set_text($vals[3]);
	 		$form->get_widget('entry_tt_period')->set_text($vals[5]);
	 		$form->get_widget('entry_tt_day')->set_text($vals[6]);
	 		$form->get_widget('entry_tt_rests')->set_text($vals[7]);	
	 		my $notes = $vals[8];
	 		if ($notes) { &write_to_statusbar($notes); }
	 		if ($rests_active) { &on_button_tt_rests_clicked; }
		}
	} else { 
		my $tw = $form->get_widget("treeview_$what".'s');
		my @paths = $tw->get_selection->get_selected_rows;
		my ($name) = "";
		my ($rests) = "";
		my ($notes) = "";
		my ($subject) = "";
		foreach my $path (@paths) {
	 		my $iter = $tw->get_model->get_iter($path); 		
	 		if ($what eq "teacher") {
				my $s = ($tw->get_model->get($iter,1));
				if (!defined $s) { $s = ""; }
				$subject = &clarify($s.','.$subject); 
				my $n = ($tw->get_model->get($iter,0));
				if (!defined $n) { $n = ""; }
				$name = &clarify($n.','.$name); 
				my $r = ($tw->get_model->get($iter,2));
				if (!defined $r) { $r = ""; }
				$rests = &clarify($r.','.$rests); 
				my $t = ($tw->get_model->get($iter,3));
				if (!defined $t) { $t = ""; }
				$notes = &clarify($t.','.$notes); 
				
				$form->get_widget("combo_entry_tt_subject")->set_text($s);
				$form->get_widget("combo_entry_tt_teacher")->set_text($n);
				$form->get_widget("entry_$what\_subjects")->set_text($subject);
	 		} else { 
				my $n = ($tw->get_model->get($iter,0));
				if (!defined $n) { $n = ""; }
				$name = &clarify($n.','.$name); 
				my $r = ($tw->get_model->get($iter,1));
				if (!defined $r) { $r = ""; }
				$rests = &clarify($r.','.$rests); 
				my $t = ($tw->get_model->get($iter,2));
				if (!defined $t) { $t = ""; }
				$notes = &clarify($t.','.$notes); 
				
				$form->get_widget("combo_entry_tt_$what")->set_text($n);
			}		 		
		}
	 	$form->get_widget("entry_$what\_name")->set_text($name); 
	 	$form->get_widget("entry_$what\_rests")->set_text($rests);		 
	 	if ($notes) { &write_to_statusbar($notes); }	
	 	if ($rests_active) { &load_rests($what); }
	}
}
sub complete_remove {
	my ($what,$iter) = @_;
	my $form = &get_form;
	my $tt = $form->get_widget("treeview_$what".'s');
	my $name = $tt->get_model->get($iter,0);
	my $where = $what;
		$where =~ s/combinations_//;
	my $sure = 'cancel';
# 1) check if user is sure
	if ($form->get_widget('radiobutton_set_delete_ask')->get_active) {
		$sure = &check(gettext("This will completely remove the entity:")."\n".
$what."\n".gettext("from the whole project. Are you sure?"));
	} elsif ($form->get_widget('radiobutton_set_delete_complete')->get_active) {
		$sure = 'yes';
	} 
	if ($sure ne 'cancel') {
		&write_to_statusbar(gettext("Deleting all definitions of ".$name));
		&forall_lists('delete',$name,undef);
	}
}
sub del_row {
	my ($what,$complete) = @_;
	my $form = &get_form;
	my $tw;
		if ($what eq 'tt') { $tw = $form->get_widget("treeview_$what");
		} else { $tw = $form->get_widget("treeview_$what".'s'); }
# handle multiple selections
	my @paths = $tw->get_selection->get_selected_rows;	
	my @iters;
	foreach my $path (@paths) {
	 	push (@iters,$tw->get_model->get_iter($path));
	}
	foreach my $iter (@iters) {
# if we are in combinations lists, offer a complete removal from tt definitions and lists
		if (!($form->get_widget('radiobutton_set_delete_single')->get_active) and 
				(($what =~ /^combinations_/) or ($complete))) {
			 &complete_remove($what,$iter);
		} elsif ($tw->get_model->iter_has_child($iter)) {
	 		my $message = "$what\n".gettext("It seems that you want to delete several underlying 
subject definitions along with their parent node.\nAre you sure?");
	 		my $sure = &check($message);
	 		if ($sure eq "ok") { 
				$tw->get_model->remove($iter); 
			}
	 	} else {
			$tw->get_model->remove($iter); 
		}
	}	
	$what =~ s/combinations_//;
	if ($what ne 'tt') { &combo_change($what.'s'); }
	&title_change;
}

sub add_row {
	my $what = $_[0];
	my $data = $_[1];
	
	my $form = &get_form;
	my $name = $form->get_widget("entry_$what\_name")->get_text;
	my $rest = $form->get_widget("entry_$what\_rests")->get_text;		
	my $tv_t = $form->get_widget("treeview_$what".'s')->get_model;
	my $sub = "";
	my $notes = "";

	if ($data) {
		$name = ${$data}[0];
		if ($what eq 'teacher') {
			$sub = ${$data}[1];
			$rest = ${$data}[2];
			$notes = ${$data}[3];
		} else {
			$rest = ${$data}[1];
			$notes = ${$data}[2];
		}
	}

	if (!$name) {
		&check(gettext("You can't append an empty entity.\nGive it a name at least..."),'error',1);	
	} else {	

	foreach my $named (split/,/,$name) {	# always allow multiple addings...
		$named = clarify($named);	# and allow them to have spaces around...
		if ($what eq "teacher") {
			if (!$data) { $sub = $form->get_widget("entry_$what\_subjects")->get_text;	 }
			
			foreach my $subj (split/,/,$sub) { # an to teacher allow even multiple subjects
	 	 		$subj = clarify($subj);
				my $row = &add_to_tree($form,'teachers',$named,$subj);
				my $rests = $tv_t->get($row,3);
				if (defined $rests) { $rest = $rest.','.$rests; } 
	 	 		$tv_t->set($row,0,$named,1,$subj,2,$rest,3,$notes);

			# add new subjects...
				my $indi = &find_clist_row("subjects",$subj);
				if ($indi eq "new") { 
					$form->get_widget('entry_subject_name')->set_text($subj);
					&add_row("subject");
				} 
	 		} #}
		} else {
			my @classname = split/ /,$named;
			if ($#classname > 0) {		# allow adding same class name for all years
				my @years = split/-/,$classname[0]; # in a form: 1-4 name of the class
				if (($#years > 0) and (int($years[0]) eq $years[0]) and (int($years[1]) eq $years[1])) {	
					shift(@classname);
					my $nam = join(' ',@classname);
					for (my $year = $years[0]; $year <= $years[1] ; $year++) {
		# and allow the same for the second field also
						my @nos = split/-/,$classname[0]; # in a form: 1-4 1-11
						if (($#nos > 0) and (int($nos[0]) eq $nos[0]) and (int($nos[1]) eq $nos[1])) {	
							shift(@classname);
							$nam = join(' ',@classname);
							for (my $yr = $nos[0]; $yr <= $nos[1] ; $yr++) {
								&just_add_row($what,"$year $yr",$rest);
							}
						} else {
		# ---------------
							&just_add_row($what,"$year $nam",$rest);
						}
					}
				} else { &just_add_row($what,$named,$rest); }
			} else { &just_add_row($what,$named,$rest); }
		}
	}
	&combo_change($what.'s');
	}
}
sub just_add_row {
	my ($what,$named,$rest) = @_;
	my $form = &get_form;
	my $tv_t = $form->get_widget("treeview_$what".'s')->get_model;
	my $row = &find_clist_row($what."s",$named);
	if ($row eq "new") { $row = $tv_t->append; 
	} else { $row = $tv_t->get_iter_from_string($row);	}
	$tv_t->set($row,0,$named,1,$rest);	
}	
sub combo_change {
	my $what = $_[0]; 
	my %list = (); 
	my $form = &get_form;
	my $tw = $form->get_widget("treeview_$what")->get_model;
	$tw->foreach(sub {
		(undef, undef, my $iter) = @_;
		my $who = $tw->get($iter,0);
		if ($who) { $list{$who} = ""; }
		return 0;
	} );
# update combinations lists
	my $store = $form->get_widget("treeview_combinations_$what");
	$store->get_model->clear;
	my @keys = keys(%list);
	foreach my $who (sort(@keys)) { $store->get_model->set($store->get_model->append,0,$who); }
# update counters
	my $label = $form->get_widget("label_$what");
	my $markup = $label->get_label;
		$markup =~ s/ \(.*\)//;
	$label->set_markup($markup." (".($#keys + 1).")");
	my $col = ($store->get_columns)[1];
		$col->set_title('('.($#keys + 1).')');
# update combos
	chop($what);	# combos names are without plural 's
	$form->get_widget("combo_tt_$what")->set_popdown_strings(sort(@keys));
	&title_change;
}

sub add_to_tree {	# creates the parent node if necessary and return iter of new line
	my ($form,$tree,$key,$value) = @_;
		my $row = &find_clist_row($tree,$key,$value); 
		my $tv_tt = $form->get_widget("treeview_$tree")->get_model;
# if there is no parent, create new one and return first child iter
		if ($row eq "new") {	
			$row = $tv_tt->insert(undef,-1);
			if ((defined $value) and ($value ne "")) {
				$tv_tt->set($row,0,$key);
				$row = $tv_tt->insert($row,-1);
			} else {
						
			}
		} else { 
#			my $row1 = &find_clist_row($tree,$key,$value);
# if there is a parent, but we have to create child, return new iter
			my @len = split/\:/,$row;
			if ($#len > 0) { #($row1 eq "new") {
				$row = $tv_tt->get_iter_from_string($row);
# if we find the child also, return it's iter
			} else {
				$row = $tv_tt->insert($tv_tt->get_iter_from_string($row),-1); 
			}
		}
	return $row;
}

sub find_clist_row {	# poisce vrstico v clisti, ki ima v prvi celici vpisan dan podatek
	my ($what, $data, $subject) = @_;	# subject is used only for tt and teachers lists...
	my $form = &get_form;
	my $tw = $form->get_widget("treeview_$what")->get_model;	 	
	my $row = "new";
	$tw->foreach(sub {	
 	 	my (undef,undef,$child_iter) = @_; 	 	 		
 	 	my $t = $tw->get($child_iter,0);
		if ((defined $t) and ($t eq $data)) {
			my $r = $tw->get_string_from_iter($child_iter); 
			$row = $r;
			if ((defined $subject) and ($subject ne "")) { # if we are checking childs also...
			  my $s = $tw->get($child_iter,1);
			  if (defined $s) {	
				if ($subject eq $s) { # if we find one, report full path	
# report two-level path if we have exact match
					$row = $r;
					return 1; 
			   } else {
# save one-level path if we find it
					$row = (split/\:/,$r)[0];
				}
			  }
			} else {
# report one-level path if we don't look for two level
				$row = (split/\:/,$r)[0];
				return 1; 
			}
		}
		return 0; 
 	} );		
# report 'new' if even first level wasn't found
	return "$row";	# we always return a string value of path - x:y:z
}

sub forall_lists {
	my ($why,$old,$new) = @_;
	my $form = &get_form;
	my %rebuild;
	my @tvs = ('teachers', 'classs', 'classrooms', 'subjects',
					'tt','combinations_teachers','combinations_subjects',
					'combinations_classrooms','combinations_classs',
					);
	my $progress = $form->get_widget('progressbar_main'); 
		$progress->set('visible' => 1);

# for all treeviews
			foreach my $tv (@tvs) {
				my $tvt = $form->get_widget('treeview_'.$tv);
				my $cols = $tvt->get_model->get_n_columns;
	# and all the rows
#				my @iters;
				$tvt->get_model->foreach(sub {
					 my (undef,$child_path,$child_iter) = @_; 	 	 		
		# and all the cells
 					 	for (my $i = 0; $i < $cols; $i++) {
							my $t = $tvt->get_model->get($child_iter,$i);	
								if ((defined $t) and ($t eq $old)) {
			# rename or delete						
									if ($why eq 'rename') {
										$tvt->get_model->set($child_iter,$i,$new);
										$rebuild{$tv} = 1;
									} elsif ($why eq 'delete') {
										$tvt->get_selection->select_iter($child_iter);
										$rebuild{$tv} = 1;
									}
								}
						}
					$progress->pulse;
					Gtk2->main_iteration;
					return 0;
				});
				if ($why eq 'delete') {
					foreach my $iter ($tvt->get_selection->get_selected_rows) {
						$iter = $tvt->get_model->get_iter($iter);
						$tvt->get_model->remove($iter);
					}
				}
			}
			$progress->set('visible' => 0);
			&write_to_statusbar(gettext("Succesful."));

	foreach my $t (keys(%rebuild)) {
		if (($t ne 'tt') and !($t =~ /combinations/)) {
		if ($rebuild{$t}) { &combo_change($t); }
		}
	}	
}

sub get_classroom {
	my ($rest,$typpe) = @_;
	my @rooms;
	my $form = &get_form;
	my $tv = $form->get_widget('treeview_classrooms')->get_model;
	$tv->foreach(sub {
 		my (undef,undef,$child_iter) = @_; 	 	 
# room notes
		my ($id,$rests,$comments) = $tv->get($child_iter,0,1,2);
		foreach my $type (split/\;/,$rests) {
			if (defined $type) {
				my @rests = split/\:/,$type;
				my $rest_type = $rests[0];
				if ($rest_type eq $typpe) {
					foreach my $rest_val (split/\,/,$rests[1]) {	
						if ($rest_val eq $rest) {
							push (@rooms, $id);					
						}
					}
				}
			}
		}
		return 0;
	});
	return @rooms;
}


return 1;
