#     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 initialization stuff and helper functions
# 29.1.2005

use strict;

sub gtk_main_quit { Gtk2->main_quit(); }

sub get_debug_data {
	my $debug = gettext("   Glib built for ").join(".", Glib->GET_VERSION_INFO).
	 		gettext(", running with ").
	     join(".", Glib::major_version, Glib::minor_version, Glib::micro_version)."\n"
	   if $Glib::VERSION >= 1.040;
	$debug = $debug.gettext("   Gtk2 built for ").join(".", Gtk2->GET_VERSION_INFO).
	 		gettext(", running with ").
	     join(".", Gtk2::major_version, Gtk2::minor_version, Gtk2::micro_version)."\n";
	return $debug;
}

sub clear_all {		# reset everything to default values
	my ($indi) = @_;
	my ($form,undef,$defined_tt_entries,$uid_tt_entries) = &get_vars;
	my @empty = ("");
	my @lists = ('teachers','classs','subjects','classrooms');
	foreach my $list (@lists) {
		$form->get_widget('treeview_'.$list)->get_model->clear;
		$form->get_widget('treeview_combinations_'.$list)->get_model->clear;
		($form->get_widget('treeview_combinations_'.$list)->get_columns)[1]->set_title('#');
		chop($list);
		$form->get_widget('entry_'.$list.'_name')->set_text("");
		$form->get_widget('combo_tt_'.$list)->set_popdown_strings(@empty);
	}
	
	$form->get_widget('treeview_tt')->get_model->clear;	
	if (!$indi) { $form->get_widget('treeview_ttview_all')->get_model->clear; }
	if (!$indi) { $form->get_widget('treeview_ttview_files')->get_model->clear; }
	
	$uid_tt_entries = ();
	$defined_tt_entries= ();    
	if (!$indi) { &clear_ttview; }
	
	$form->get_widget('entry_tt_day')->set_text("");
	$form->get_widget('entry_tt_period')->set_text("");
	$form->get_widget('entry_tt_perweek')->set_text("");
	
	$form->get_widget('label-chromo')->set_text("");
	if (!$indi) { $form->get_widget('combo_tt_result')->set_popdown_strings(@empty); }

	$form->get_widget('entry_title')->set_text("");
	$form->get_widget('entry_notes')->set_text("");
	$form->get_widget('entry_author')->set_text("");
	$form->get_widget('entry_days')->set_text("5");
	$form->get_widget('entry_periods')->set_text("14");
	$form->get_widget('entry_impossible')->set_text("50");
	$form->get_widget('entry_encoding')->set_text("utf-8");

	$form->get_widget('entry_mod_opts')->set('visible',0);
	$form->get_widget('label_mod_opts')->set('visible',0);	
	$form->get_widget('button_mod_opts_use')->set('visible',0);

	my $oldtable = $form->get_widget('viewport-result')->get_child;
	if ($oldtable) { $form->get_widget('viewport-result')->remove($oldtable); }
		
#	&set_modules_path($form);
	&load_modules($form);
	
	$form->get_widget('window_main')->set_title(gettext("G-Tablix - Untitled"));
}
sub write_to_statusbar {
	my ($what) = @_;
	my $form = &get_form;
		my $cid = $form->get_widget('statusbar')->get_context_id($what);
		$form->get_widget('statusbar')->push($cid,$what);		
}

sub check {
	my ($message,$type,$mode) = @_;
	my $form = &get_form;
	if ($mode) {
		my $color = new Gtk2::Gdk::Color(65535,32000,0);	# orange for errors
		if ($type ne 'error') {
			$form->get_widget('button_toolbar_ok')->set('visible' => 1);
			$color = new Gtk2::Gdk::Color(0,50000,0);	# green for sugestions
		}
		$form->get_widget('button_toolbar_cancel')->set('visible' => 1);		
		$form->get_widget('eventbox_toolbar_label_ok')->set('visible' => 1);
		
		$form->get_widget('eventbox_toolbar_label_ok')->modify_bg('normal',$color);
		$form->get_widget('label_toolbar_ok')->set_markup($message);	
	} else {
		my %butns = ('error' => 'ok', 
						'question' => 'ok-cancel', 
						'info' => 'ok', 
						'warning' => 'yes-no');
		if (!$type) { $type = "question"; }
		my $main = $form->get_widget('window_main');
		my $dlg = Gtk2::MessageDialog->new($main, ['modal'], $type, $butns{$type},$message);
		my $response = $dlg->run;
		$dlg->destroy;
		return $response;
	}
}

sub find_browser {
	my @try = ('firefox','galeon','konqueror','mozilla','opera','dillo');
	foreach my $a (@try) {
		my $b = readpipe("whereis $a");
		$b = (split/ /,$b)[1];
		if (-x $b) { return $b; }
	}
	return 0;
}

sub get_filename {
	my ($why, $title, $dir, $multi) = @_;
	my $chooser = new Gtk2::FileChooserDialog($title, undef, $why, 
							'gtk-ok' => 'ok', 'gtk-cancel' => 'cancel');
	if (defined $multi) { $chooser->set_select_multiple(1); }
	if (!$dir) {
	 	if ($why eq 'save') {
			my $type = new Gtk2::CheckButton (gettext('Use Tablix 2 format'));
			$type->set_active (1);
			$chooser->set_extra_widget($type);
		}
		
		my $filter = new Gtk2::FileFilter();
	 	$filter->add_pattern('*');
	 	$filter->set_name(gettext('All Files (*.*)'));
	 	$chooser->add_filter($filter);	

	 	my $filter2 = new Gtk2::FileFilter();
	 	$filter2->add_mime_type('text/xml');
	 	$filter2->set_name(gettext('Timetable files (*.XML)'));
	 	$chooser->add_filter($filter2);
	 
	 	my $filter3 = new Gtk2::FileFilter();
	 	$filter3->add_mime_type('application/x-gzip');
	 	$filter3->set_name(gettext('Gziped files (*.gz)'));
	 	$chooser->add_filter($filter3);	

	 	my $filter4 = new Gtk2::FileFilter();
	 	$filter4->add_mime_type('text/html');
	 	$filter4->set_name(gettext('HTML files (*.html)'));
	 	$chooser->add_filter($filter4);	
	}	
	if ($chooser->run eq "ok") {	  
		my $filename;
		my $type;
		if ($dir) { 
			$filename = $chooser->get_current_folder();
		} elsif ($multi) {
			my @filename = $chooser->get_filenames();
			$chooser->destroy;
			return (@filename);
		} else { 
			if ($why eq 'save') {
				$type = $chooser->get_extra_widget->get_active;
				$type++;
			}
			$filename = $chooser->get_filename(); 
		}
		$chooser->destroy;
		return ($filename,$type);
	}
	$chooser->destroy;
	return "cancel";  
}
sub strip_commas { 	# odstej podniz in/ali pobrisi podvojene, vodilne ali zadnje vejice v nizu
	my ($string,$substring) = @_;
	if ($substring) { $string =~ s/$substring//g; }
	$string =~ s/^\,//g;
	$string =~ s/\,$//g;
	$string =~ s/\,\,/\,/g;
	return $string;
}
sub get_process {
	my ($name) = @_;
	my @lines = split /\n/, readpipe("ps ax |grep $name");
	if ($#lines > 0) { return 1; } else { return 0; }
}
sub get_format {
	my ($what) = @_;
	if (!defined $what) { $what = 'svg'; }
# we expect png to work always, but want to use svg because it's faster
	my $format = 'png';
	foreach my $desc (Gtk2::Gdk::Pixbuf->get_formats) {
		if ($desc->{name} eq $what) { $format = $what; last; }
	}
	return $format;
}

sub title_change {
	my $form = &get_form;	
	my @title = split/ - /,$form->get_widget('window_main')->get_title;
	if ($#{title} != 2) { 
		$form->get_widget('window_main')->set_title($title[0]." - ".$title[1]." - ".gettext("Unsaved")); }
}

sub clarify {
	my ($what) = @_;
	if (defined $what) {
		$what =~ s/^ *//g;
		$what =~ s/ *$//g;
		$what =~ s/^,*//g;
		$what =~ s/,*$//g;
		$what =~ s/  / /g;
		$what =~ s/,,/,/g;
	}
	return $what;
}

sub draw_context_menu {
	my ($where,$now,$what) = @_;
	my $form = &get_form;	
   my $menu = new Gtk2::Menu;
# everybody
   my %items;
	if ($what =~ /ttview/) {
		%items = (gettext("Help / Wizard") => sub { &on_wizard1_activate; },
					gettext("Export to file") => sub { &on_exportresult_activate; }
					);
		if ($what eq 'ttview_files') {
			$items{gettext("Remove from list")} = sub { &ttview_file_remove; },
			$items{gettext("Import to list")} = sub { &on_importresult_activate; }
		}
	} else {
		%items = (gettext("Edit Restrictions") => sub { &load_rests("$what"); },
					gettext("Help / Wizard") => sub { &on_wizard1_activate; },
					gettext("Rename") => sub { &edit_cell($what,$where); }
   				);
	 # teachers and tt
	    if ($what eq 'teacher') {
	 		$items{gettext("Select all")} = sub { &select_all("$what"); };
	 		$items{gettext("Expand / Collapse All")} = sub { &toggle_fold($what); };
	 		$items{gettext("Delete Row(s)")} = sub { &del_row("$what"); };
	 		$items{gettext("Complete remove")} = sub { &del_row("$what",1); };
	 	} elsif ($what eq 'tt') {
	 		$items{gettext("Select all")} = sub { &select_all("$what"); };
	 		$items{gettext("Delete Row(s)")} = sub { &del_row("$what"); };
	 		$items{gettext("Expand / Collapse All")} = sub { &toggle_fold($what); };
	 # combinations
	 	} elsif ($what =~ /combinations/) {
#	 		$items{gettext("Select all")} = sub { &select_all("$what"); };
	 		$items{gettext("Complete remove")} = sub { &del_row("$what",1); };
	 # all other
	 	} else {
	 		$items{gettext("Select all")} = sub { &select_all("$what"); };
	 		$items{gettext("Complete remove")} = sub { &del_row("$what",1); };
	 		$items{gettext("Delete Row(s)")} = sub { &del_row("$what"); };
	 	}
	}
	while (my ($name, $callback) = each (%items)) {
		my $menu_item = Gtk2::MenuItem->new($name);
		$menu_item->signal_connect('activate', $callback);
		$menu->append($menu_item);
		$menu_item->show();
   }

	my %lists = ('teacher' => 1, 'subject' => 1, 'classroom' => 1, 'class' => 1, 'tt' => 1);
	if ($lists{$what}) {
		&create_mod_context ($menu, $what);
	}

   $menu->popup(undef,undef,undef,undef,$now->button,$now->time);
}

sub select_all {
	my ($what) = @_;
	my $form = &get_form;	
	$form->get_widget("treeview_$what".'s')->get_selection->select_all;	
}
sub edit_cell {
	my ($what, $where) = @_;
	my ($path,$col) = $where->get_cursor;
	if (defined $path) { $where->set_cursor_on_cell ($path,$col,undef,1); }
}
sub rename_entity {
# this gets called whenever user manualy rewrites some entities name in the list
# we must search for this entity in other lists and rename appropriatly.
	my ($what,$old_text,$new_text) = @_;
	my $form = &get_form;
	if ((defined $old_text) and (defined $new_text) and ($old_text ne $new_text)) {
		#my $ok = &check(gettext("Do you want to rename all definitions of this entity in the project?"));
		if ($form->get_widget('radiobutton_set_rename_ask')->get_active) {
			&check(gettext("Do you want to <b>rename</b> all definitions of".
								' <b>'.$old_text.'</b> '.gettext("in the project to".
								' <b>'.$new_text."</b>?")),'check',1);
				$form->get_widget('button_toolbar_ok')->signal_connect('clicked' => sub {
					&write_to_statusbar(gettext("Looking for definitions to rename..."));
					&forall_lists ('rename',$old_text,$new_text);
					&on_button_toolbar_cancel_clicked;
				}); 
		} elsif ($form->get_widget('radiobutton_set_rename_complete')->get_active) {
			&write_to_statusbar(gettext("Looking for definitions to rename..."));
			&forall_lists ('rename',$old_text,$new_text);
			&on_button_toolbar_cancel_clicked;	
		}
	}
}
# ------------------------- I/O -----------------------------
sub save_file {		# shrani datoteko
	my ($filename,$how,$export) = @_;
	my ($form,undef,$defined_tt_entries,$uid_tt_entries) = &get_vars;
#	my $encoding = $form->get_widget('entry_encoding')->get_text;
# napolni $filename
	# how: 1 / 2
	my $output = &generateXML($filename,$form,$defined_tt_entries,$uid_tt_entries,$how);
 	if (-e $filename) { system("mv -f $filename $filename.bak"); }
		$filename =~ /\.(.*)$/;
	my $type = $1;
	if (!$type) { $type = 'xml'; $filename .= '.xml'; }
	if ($type eq 'gz') {
		open (XML,"| gzip > $filename");
		#open (XML,"|iconv -f utf8 -t $encoding | gzip > $filename");
		print XML $output;
		close XML;	
	} elsif ($type eq 'xml') {
		open (XML,">$filename");
		#open (XML,"|iconv -f utf8 -t $encoding -o $filename");
		print XML $output;
		close XML;	
	}	
	if (!$export) { $form->get_widget('window_main')->set_title("G-Tablix - $filename"); }	# export or save
	&write_to_statusbar(gettext("File")." $filename ".gettext("successfuly saved."));
	&push_recent($filename);
}
sub import {
	my ($filename, $what) = @_;
	my $form = &get_form;
 if (!-r $filename) {
  		&check(gettext("Couldn't open file")."\n$filename\n".
			 gettext("Check full path and permissions"),'error',1);
  } else {
	my $errors;
#	my $encoding = $form->get_widget('entry_encoding')->get_text;

# i18n
	my @whats = ('Classes','Teachers','Subjects','Classrooms');
	foreach my $whats (@whats) { if ($what eq gettext($whats)) { $what = $whats; } }
	$what =~ tr/A-Z/a-z/;
	if ($what eq "classes") { $what = "classs"; }

	my $tw = $form->get_widget("treeview_$what")->get_model;	

	my $type = &get_file_type($filename);
	if ($type eq 'gzip') {
		open(WHAT, "gunzip -c $filename");
	} else {	
		open(WHAT, "<:utf8", "$filename");
	}
	while (my $line = <WHAT>) {
		chop $line;
		$line =~ s/^ *//g;
		$line =~ s/ *$//g;
		my @what = split/\t/,$line;
		if (defined $what[0]) {
			my $wh = $what;
			$wh =~ s/s$//;
			&add_row($wh,\@what);
#		}		
#			if ($what eq "teachers") { 
#				&add_row($what,@what);
#				$tw->set($tw->append(undef),0,$what[0],1,$what[1],2,$what[2]); 
#			} else { 
#				$tw->set($tw->append(),0,$what[0],1,$what[1]); }		
		} #else { $errors = $errors."\t$line\n"; } 
	}
	close WHAT;
	&combo_change($what);
#	if ($errors) {
#		my $message = "\n\n  ".gettext("Errors while importing:")."\n$errors\n";
#		&check($message,"error");
#	} else {
		&write_to_statusbar(gettext("File")." $filename ".
									gettext("successfuly imported").".");
#	}
  }
}
sub export {
	my ($filename, $what) = @_;
	my $form = &get_form;

	my @file = split/\./,$filename;
	my $type = pop(@file);
	if ($type eq 'gz') {
		$filename = join('.',@file);
	}
	if (-e $filename) { system("mv $filename $filename.bak"); }

# i18n
	my @whats = ('Classes','Teachers','Subjects','Classrooms');
	foreach my $whats (@whats) { if ($what eq gettext($whats)) { $what = $whats; } }
	$what =~ tr/A-Z/a-z/;
	if ($what eq "classes") { $what = "classs"; }

	my $tw = $form->get_widget("treeview_$what")->get_model;
	open (WHAT,">$filename");
	$tw->foreach(sub {
		(undef, undef, my $iter) = @_;
		my $who = $tw->get($iter,0);
		my $for = $tw->get($iter,1);
		my $how = $tw->get($iter,2);
		if (!defined $for) { $for = ""; }
		if (!defined $how) { $how = ""; }
		if (defined $who) { print WHAT "$who\t$for\t$how\n"; }
		return 0;
	} );
	close WHAT;	
	if ($type eq 'gz') {
		system ("gzip $filename");
	} 
	&write_to_statusbar(gettext("Sucessfully exported to file ").$filename);
}

return 1;
