#     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 with basic gui handlers...
# 19.12.2004, 30.1.2005

#package gtablix::gui;

use strict;

sub on_treeview_modules_cursor_changed {		# output the apropriate description
	my $form = &get_form;
	my $tvm = $form->get_widget('treeview_modules');
		(my $path, my $col) = $tvm->get_cursor(); 
		my $iter = $tvm->get_model->get_iter($path);

# get data
	my ($name,$opts,$notes) = $tvm->get_model->get($iter,0,4,5);

# write module description
	&mod_desc($form,$name); 

# write options
	&mod_opts($form,$name,$opts);

# write notes	
	if ($notes) { &write_to_statusbar($notes);
	} else {	&write_to_statusbar(""); }
}

sub on_button_toolbar_cancel_clicked {
	my $form = &get_form;
		$form->get_widget('eventbox_toolbar_label_ok')->set('visible' => 0);
		$form->get_widget('button_toolbar_ok')->set('visible' => 0);	
		$form->get_widget('button_toolbar_cancel')->set('visible' => 0);	
}
sub on_window_main_delete_event { &on_quit1_activate; }
sub on_entry_temp_activate { &on_button_open_temp_clicked; }
sub on_entry_temp_editing_done {	&set_tablix_command_line; }
sub on_button_open_temp_clicked {
	my $form = &get_form;
	my ($folder) = &get_filename('open',gettext('Select directory for tablix temporary files'),1);
	if ($folder ne 'cancel') {	
		$form->get_widget('entry_temp')->set_text($folder);
	}
}
sub on_button_modpathuse_clicked { 
	my $form = &get_form;
	my ($folder) = &get_filename('open',gettext('Select directory with tablix modules'),1);
	if ($folder ne 'cancel') {	
		$form->get_widget('entry_modpath')->set_text($folder);
		&load_modules; 
	}
}
sub toggle_fold {
	my ($what) = @_;
	my $form = &get_form;	
	if ($what eq 'teacher') { $what = 'teachers'; }	
	my $how = $form->get_widget("togglebutton_fold_$what")->get_active;
	$form->get_widget("togglebutton_fold_$what")->set_active(!$how);
}
sub on_togglebutton_fold_tt_toggled { &folding('tt'); }
sub on_togglebutton_fold_teachers_toggled { &folding('teachers'); }
sub folding {
	my ($what) = @_;
	my $form = &get_form;	
	my $tv = $form->get_widget("treeview_$what");
	my $me = $form->get_widget("togglebutton_fold_$what");
#	my $icon = $me->get_child;
	if ($me->get_active) {
		$tv->expand_all;
#		$icon->set_from_stock('gtk-remove','button');
		$tv->queue_draw;
	} else { 
		$tv->collapse_all;
#		$icon->set_from_stock('gtk-add','button');
	}
}
sub on_button_mod_opts_use_clicked {
	my $form = &get_form;
	my $tvm = $form->get_widget('treeview_modules');
		(my $path, my $col) = $tvm->get_cursor(); 
		my $iter = $tvm->get_model->get_iter($path);
	$tvm->get_model->set($iter,3,"1",4,$form->get_widget('entry_mod_opts')->get_text);
}

sub on_about1_activate { 
# TODO: get this from file
	my $form = &get_form;
	my $picdir = &get_picdir;
	my $docdir = &get_doc;
	my $debug = &get_debug_data;
	my $version = &get_version;
	my $locale = setlocale(LC_MESSAGES);
	my $message = "<span size=\"larger\"><b>G-Tablix</b>\n".
gettext("graphical frontend for Tablix")."</span>\n\n".
gettext('<b>'."Version:".'</b>')."\n".$version."\n".
gettext('<b>'."Homepage:".'</b>')."
http:://gtablix.homelinux.org\n".
gettext('<b>'."Author:".'</b>')."
Bostjan Spetic, igzebedze\@kiberpipa.org\n".
gettext('<b>'."Contributions from:".'</b>')."
Tomaz Solc, R. Quenett, Antonio Duran, Vadim Basilevich, Francesco Zamboni\n\n$debug Locale: $locale";
        
        my $gnu = readpipe("more $docdir/COPYING");
        if ($gnu eq "") { $gnu = "G-Tablix version $version, Copyright (C) 2005, 2006 Bostjan Spetic
G-Tablix comes with ABSOLUTELY NO WARRANTY; for detailes see Licence.
This is free software, and you are welcome to redistribute it under certain conditions; see Licence for detailes.";  }
	my $main = $form->get_widget('window_main');
	my $dlg = Gtk2::Dialog->new('About gTablix',$main, ['modal'], 'close' => 'close');
	my $book = new Gtk2::Notebook;
#	my $gnuu = Gtk2::Label->new;
#	  $gnuu->set_text($gnu);

	my $layout = new Gtk2::ScrolledWindow();
	my $text = new Gtk2::TextView();
	my $notice = new Gtk2::TextBuffer(); 
		$text->set_editable(0);
		$text->set_buffer($notice);		
	$layout->add($text);
	$notice->insert($notice->get_start_iter,$gnu);

	my $label = Gtk2::Label->new;
		$label->set_justify('center');
		$label->set_markup($message);
	my $image = Gtk2::Image->new_from_file($picdir.'/tablix-chrome.png');
	my $hedge = Gtk2::Image->new_from_file($picdir.'/jezek-64_L.png');
		$hedge->set_alignment(1,0);
	$dlg->vbox->add($image);
	$dlg->vbox->add($hedge);
	$dlg->vbox->add($book);
	  $book->append_page($label,gettext('About'));
	  $book->append_page($layout,gettext('License'));
	#$dlg->vbox->add($label);
	$dlg->show_all;
	$dlg->run;
	$dlg->destroy;
}
sub on_manual1_activate { 
	my $browser = &find_browser;
#	my $helpfile = &get_help;
#	if (!-e $helpfile) {
#		&check("I couldn't find help file $helpfile.\nDid you install gtablix-doc?",'error');
#	} else {
	if ($browser) { system("$browser http://gtablix.homelinux.org");#file://$helpfile &"); 
	} else { &check(gettext("I couldn't find web browser in your path.
Navigate to http://gtablix.shacknet.nu manually."),'error',1); }
#	}
}
sub menu_import {
	my $what = $_[0]->get_children->get_text;
	my ($filename) = &get_filename("open","Import $what list");
	if ($filename ne "cancel") { &import($filename, $what); }
}
sub menu_export {
	my $what = $_[0]->get_children->get_text;
	my ($filename) = &get_filename("save","Eport $what list");
	if ($filename ne "cancel") { &export($filename, $what); }
}

# ---- menu items ----------------------------

sub on_xpvm1_activate {  system ("xpvm&"); }
sub on_clusterconf1_activate {  
	my $ok = &check(gettext("Clusterconf is prepared for use in live Linux distributions.
it's not recommended to use it in any other case. Are you sure?"));
	if ($ok eq 'ok') { system ("clusterconf&"); }
}
sub on_check1_activate { &on_toolbutton_test_clicked }
sub on_toolbutton_new_clicked { &on_clear1_activate; }
sub on_toolbutton_open_clicked { &on_open1_activate; }
sub on_toolbutton_save_clicked { &on_save1_activate; }
sub on_toolbutton_saveas_clicked { &on_save_as1_activate; }
sub on_toolbutton_quit_clicked { &on_quit1_activate; }
sub on_toolbutton_test_clicked { &do_internal_test(&get_form); }
sub on_toolbutton_stats_clicked { &statistics(&get_form); }
sub on_toolbutton_help_clicked { &on_quick_help1_activate; }
sub on_restrictions1_activate {  
	my $form = &get_form;
	$form->get_widget('toggletoolbutton_options')->set_active(1);
}
sub on_quick_help1_activate { 
	my (undef,undef,$help) = &get_help;
	if (-e $help) {
#		open(WHAT, "<:utf8", "$help");
		$help = readpipe("more $help");
#		while (my $h = <WHAT>) {
#			$help = $help.$h;
#		}
#		close WHAT;
		&check($help,'info');
	} elsif (-e $help.'.gz') {
                $help = readpipe ("gunzip -c $help.gz");
                &check($help,'info');
	} 
}
# --------- menus ---------------
sub on_open1_activate { 
	my ($form,undef,$defined_tt_entries,$uid_tt_entries) = &get_vars;
	my ($filename) = &get_filename("open",gettext("Open file"));
	if ($filename ne 'cancel') {
		&on_clear1_activate;
		&parse_xml($filename,$form,$defined_tt_entries,$uid_tt_entries);
		&push_recent($filename);
	}
}
sub on_save1_activate {
	my $form = &get_form;
	my $filename = (split/ - /,($form->get_widget('window_main')->get_title))[1];
	if ($filename ne gettext("Untitled")) { 
		&save_file($filename,1,0);
	} else { &on_save_as1_activate; };
}
sub on_save_as1_activate { 
	my ($filename,$type) = &get_filename("save",gettext("Save as"));
	if ($filename ne 'cancel') { &save_file($filename,$type,0); }
}
sub on_clear1_activate {
	my $form = &get_form;
	my $changed = (split/ - /,($form->get_widget('window_main')->get_title))[2];
  	if ($changed and ($changed eq "Unsaved")) { 
		my $message = gettext("\n\tAre you sure to clear all data,\n\t and loose all changes?\t\n");
		my $sure = &check($message);
		if ($sure ne "ok") { return 0; }
	}	
	&clear_all;
}
sub on_quit1_activate {
	my $form = &get_form;
	my $changed = (split/ - /,($form->get_widget('window_main')->get_title))[2];
	if ($changed) { 
		my $message = gettext("\n\tDo you want to save changes\nbefore you quit?\t\n");
		my $sure = &check($message,'warning');
		if ($sure eq "yes") { &on_save1_activate; } 
		elsif ($sure eq 'delete-event') { return 0; }  
	}
	&on_button_set_ok_clicked;
	Gtk2->main_quit;
}
sub on_wizard1_activate {
	my $form = &get_form;
	my $what = $form->get_widget('togglebutton_wizard')->get_active;
	$form->get_widget('togglebutton_wizard')->set_active(!$what);
}
sub on_toolbutton_use_clicked { 	# add the combination of selected teacher-subject-class-room to timetable definition
	my $form = &get_form;
	my $class = $form->get_widget('entry_class_name')->get_text;
	my $classroom = $form->get_widget('entry_classroom_name')->get_text;
	my $perweek = $form->get_widget('entry_fast_perweek')->get_text;
	my $day = "0"; 
	my $period = "0";
	
		my $tw = $form->get_widget('treeview_teachers');
		(my $path, undef) = $tw->get_cursor(); 
		my $iter = $tw->get_model->get_iter($path);
	(my $teacher, my $subject) = $tw->get_model->get($iter,0,1);	

		# one cannot deselect classroom, so it always looses in favor of perweek
		if (defined $perweek) { 
			$perweek = int($perweek);
			$day = "";
			$period = "";
			if (defined $classroom) { $classroom = ""; }
		} 	# but if perweek is not selected, the room and the default day and period will get inserted
	 	$form->get_widget('combo_entry_tt_teacher')->set_text($teacher);
	 	$form->get_widget('combo_entry_tt_subject')->set_text($subject);
	 	$form->get_widget('combo_entry_tt_classroom')->set_text($classroom);
	 	$form->get_widget('combo_entry_tt_class')->set_text($class);
	 	$form->get_widget('entry_tt_perweek')->set_text($perweek);
	 	$form->get_widget('entry_tt_period')->set_text($period);
	 	$form->get_widget('entry_tt_day')->set_text($day);
	 	$form->get_widget('entry_tt_rests')->set_text("");	
		&on_button_tt_use_clicked;

	$form->get_widget('entry_fast_perweek')->set_text("");
}
sub on_settings2_activate {
	&get_form->get_widget('window_settings')->set('visible' => 1);
}
# --------- teachers ------------
sub on_button_teachers_del_clicked { &del_row("teacher"); } 
sub on_button_teachers_use_clicked { &add_row("teacher"); }
sub on_button_teacher_add_subject_clicked {
	my $form = &get_form;
 	my $name = $form->get_widget('entry_teacher_name')->get_text;
 	my $olds = $form->get_widget('entry_teacher_subjects')->get_text;
 	my $new = $form->get_widget('entry_subject_name')->get_text;
	$form->get_widget('entry_teacher_subjects')->set_text(&clarify($new.','.$olds));
	&add_row("teacher");
}
sub on_button_teacher_rests_clicked { &load_rests("teacher"); }	# the same restrictions as for subjects
# --------- classrooms ----------
sub on_button_rooms_del_clicked { 
	my $form = &get_form;
	my $entry = $form->get_widget('entry_classroom_name');
	my @cs = split/ - /,$entry->get_text;
	if ($#cs > 0) {
		for (my $c = $cs[0]; $c <= $cs[1]; $c++) {
			$entry->set_text($c);
			&del_row("classroom"); 
		}
	} else { &del_row("classroom"); }
}
sub on_button_rooms_use_clicked { 
	my $form = &get_form;
	my $entry = $form->get_widget('entry_classroom_name');
	my @cs = split/ - /,$entry->get_text;
	if ($#cs > 0) {
		for (my $c = $cs[0]; $c <= $cs[1]; $c++) {
			$entry->set_text($c);
			&add_row("classroom"); 
		}
	} else { &add_row("classroom"); }
} 
sub on_button_rooms_rests_clicked { &load_rests("classroom"); }
# --------- classes -------------
sub on_button_classes_del_clicked { &del_row("class"); }
sub on_button_classes_use_clicked { &add_row("class"); } 
sub on_button_classes_rests_clicked { &load_rests("class"); }
# --------- subjects ------------
sub on_button_subjects_del_clicked { &del_row("subject"); }
sub on_button_subjects_use_clicked { &add_row("subject"); }
sub on_button_subjects_rests_clicked { &load_rests("subject"); }
# --------- for all tvs ----------------------------------------------
sub on_treeview_cursor_changed { 
	my ($where, $now) = @_;
	my $name = $where->get_name;
		$name =~ s/treeview_//;
		chop($name);
	&select_row($name);
}
sub on_treeview_button_release_event { 	
	my ($where, $now) = @_;
	my $name = $where->get_name;
		$name =~ s/treeview_//;
		chop($name);
	
	if (($_[1]->button == 3)) { 
		&draw_context_menu ($where,$now,$name); 
#	} elsif (($_[1]->button == 1)) { 
#		&select_row($name);
	}
}
sub on_treeview_key_press_event { 
	my ($where, $now) = @_;
	my $name = $where->get_name;
		$name =~ s/treeview_//;
		chop($name);
	
	if ($now->keyval == $Gtk2::Gdk::Keysyms{Delete}) {
		my @paths = $where->get_selection->get_selected_rows;
		if ($paths[0]) { 
	# ugly
			if ($name eq 'classroom') { 
				&on_button_rooms_del_clicked;
			} else {	&del_row($name); }
		}
	}
}
################################################################
sub on_entry_times_changed {
	my ($where, undef,$name) = @_;
	if (!defined $name) {
		$name = $where->get_name;
		$name =~ s/entry_//;
	}
	my $Name = $name;
		chop($Name);
		$Name = ucfirst($Name);
	
	my $form = &get_form;
	my $entry = $form->get_widget("entry_".$name)->get_text;

	my $table = $form->get_widget('table_set_'.$name);
	foreach my $cell ($table->get_children) { $cell->destroy; }	

	my @count;
	if ($entry ne "") {
	 	for (my $i = 0; $i < int($entry); $i++) {
	 		push (@count,$i);
		my $label = new Gtk2::Label(gettext($Name)."$i:");
			$table->attach_defaults($label,0,1,$i,($i + 1));
			$label->set_justify('right');
		my $entry = new Gtk2::Entry();
			$table->attach_defaults($entry,1,2,$i,($i + 1));
			$entry->set_name("entry_$i");
	 	}
	 	$form->get_widget("combo_tt_".$name)->set_popdown_strings("",@count);
	 	&mini_tt;
	}	
	$table->show_all;
}

# --- pressing enter -----------------

sub on_combo_entry_tt_teacher_activate { &tt_keypress; }
sub on_combo_entry_tt_class_activate { &tt_keypress; }
sub on_combo_entry_tt_subject_activate { &tt_keypress; }
sub on_combo_entry_tt_classroom_activate { &tt_keypress; }
sub on_entry_tt_day_activatet { &tt_keypress; }
sub on_entry_tt_period_activate { &tt_keypress; }
sub on_entry_tt_perweek_activate { &tt_keypress; }
sub on_entry_tt_rests_activate { &tt_keypress; }
sub tt_keypress { &on_button_tt_use_clicked; }
sub on_entry_teacher_name_activate { &on_button_teachers_use_clicked; }
sub on_entry_teacher_subjects_activate{ &on_button_teachers_use_clicked; }
sub on_entry_teacher_rests_activate{ &on_button_teachers_use_clicked; }
sub on_entry_subject_name_activate{ &on_button_subjects_use_clicked; }
sub on_entry_subject_rests_activate{ &on_button_subjects_use_clicked; }
sub on_entry_classroom_name_activate{ &on_button_rooms_use_clicked; }
sub on_entry_classroom_rests_activate{ &on_button_rooms_use_clicked; }
sub on_entry_class_name_activate{ &on_button_classes_use_clicked; }
sub on_entry_class_rests_activate{ &on_button_classes_use_clicked; }
sub on_entry_modpath_activate{ &load_modules;  }
sub on_entry_mod_opts_activate{ &on_button_mod_opts_use_clicked; }

# ----tt menu ------------------------------

sub goto_book {
	my ($name) = @_;
	my $form = &get_form;
	my $notebook = $form->get_widget('notebook1');
	$notebook->set_show_tabs(1);
	if ($name eq 'select') { $notebook->set_current_page(0);
	} elsif ($name eq 'settings') { $notebook->set_current_page(1);
	} elsif ($name eq 'classrooms') { 
		$notebook->set_current_page(2);
		$form->get_widget('notebook_switch_lists')->set_current_page(0);
	} elsif ($name eq 'classes') { 
		$notebook->set_current_page(2);
		$form->get_widget('notebook_switch_lists')->set_current_page(1);
	} elsif ($name eq 'subjects') { 
		$notebook->set_current_page(2);
		$form->get_widget('notebook_switch_lists')->set_current_page(2);
	} elsif ($name eq 'teachers') { $notebook->set_current_page(2);
	} elsif ($name eq 'editor') { $notebook->set_current_page(3);
	} elsif ($name eq 'tt_lists') { $notebook->set_current_page(3);
	} elsif ($name eq 'modules') { $notebook->set_current_page(1);
	} elsif ($name eq 'tablix') { $notebook->set_current_page(4);
	} elsif ($name eq 'plot') { $notebook->set_current_page(4);
	} elsif ($name eq 'result') { $notebook->set_current_page(5);
	} 
}
sub on_settings1_activate { &goto_book('settings'); }
sub on_modules1_activate { &goto_book('settings'); }
sub on_teachers1_activate { &goto_book('teachers'); }
sub on_classes1_activate { &goto_book('classes'); }
sub on_classrooms1_activate { &goto_book('classrooms'); }
sub on_subjects1_activate { &goto_book('subjects'); }
sub on_definition1_activate { &goto_book('editor'); }
sub on_generate1_activate { &goto_book('tablix'); }
sub on_manage_results1_activate { &goto_book('result'); }

# ------------------------------------------

sub open_recent {
	my $what = $_[0]->get_children->get_text;
	my ($form,undef,$defined_tt_entries,$uid_tt_entries) = &get_vars;
	if (-e $what) { &parse_xml($what,$form,$defined_tt_entries,$uid_tt_entries); }	
}

# -----------------------------------------

return 1;
