#!/usr/bin/perl -w
#
# G-Tablix, graphical user interface for Tablix
# author: Bostjan Spetic, igzebedze@cyberpipe.org
# contributions: Tomaz Solc
# 19.12.2004, 30.1.2005

# ---------------------- check these for your system...

#package main;

# use these for local directory runs
#my $libdir = readpipe("pwd"); 
#chop $libdir;

# use these for packaged distributions
use lib "/usr/lib";
my $libdir = "/usr/lib";

# other settings
my $helpfile = "/usr/share/doc/gtablix/help.html";
my $tempdir = "/tmp/gtablix";

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

use strict;
use Glib qw(TRUE FALSE);
use Gtk2 '-init';    
use Gtk2::GladeXML;
use Gtk2::SimpleList; 

use gtablix::check;
use gtablix::xml;
use gtablix::modinfo;
use gtablix::helpers;
use gtablix::gui;
use gtablix::plot;
use gtablix::ttview;
use gtablix::wizard;
#use gtablix::stats;

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

my $form = Gtk2::GladeXML->new("$libdir/gtablix/gtablix.glade");
$form->signal_autoconnect_from_package('main');
		
my %modules;		# modules infos
my %defined_tt_entries; my %uid_tt_entries;
	#$uid_tt_entries{$i} = "$class||$title||$teacher";
	#$defined_tt_entries{"$room||$period||$day"} = $class||$title||$teacher;

&prep_tvs($form);					# create simplelists
&check_deps;		# check if all internally used programs are present
&set_module_path($form);		# check tablix's module path
&load_modules($form);			# check tablix's modules and fillup %modules
&check_opts(shift(@ARGV),$form,\%defined_tt_entries,\%uid_tt_entries);	 # check command line options

#$form->get_widget('notebook1')->set_current_page(5);
#$form->get_widget('togglebutton_wizard')->set_active(0);	# start the wizard
&write_to_statusbar('Welcome to G-Tablix.');

#&init_wizard;

Gtk2->main;

# --------- gui handlers -----------------------------------

sub load_modules { 		# Load accesible modules and descriptions into "modules" clist.
#	my ($form) = @_;
	my $path = $form->get_widget('entry_modpath')->get_text;
	if (!-d $path) {
		&check("The modules path is not a directory.\nTablix modules will not work.",'error');
	} elsif (!-r $path) {
		&check("The modules directory is not readable.\nTablix modules will not work.",'error');
	} else {
		opendir(MODULEDIR,$path);
		my @mods = readdir(MODULEDIR);
		closedir(MODULEDIR);
	
	 	%modules = ();
	 	my $tv_m = $form->get_widget('treeview_modules')->get_model;
		$tv_m->clear;
			foreach my $mod (@mods) {
	 		if(($mod=~/\.so/)&&($mod!~/export/)) {
	 			my $row = $tv_m->append; 
	 			$tv_m->set($row,0,$mod,1,0,2,0,3,0,4,"");
				$modules{$mod} = readpipe("tablix_modinfo $mod");
	 		}
	 	}
	}
# load possible timetable export functions
	my @exports	= ("Individual","All Individuals","Combined","Styled Combined");
	$form->get_widget("combo_tt_exports")->set_popdown_strings(@exports);
# setup the days and periods combos	
	&on_entry_periods_changed;
	&on_entry_days_changed;
	$form->get_widget('checkbutton_additive')->set_active(1);
}

sub on_treeview_modules_cursor_changed {		# output the apropriate description
	my $tvm = $form->get_widget('treeview_modules');
		(my $path, my $col) = $tvm->get_cursor(); 
		my $iter = $tvm->get_model->get_iter($path);
	my ($name,$opts,$notes) = $tvm->get_model->get($iter,0,1,2);
	my $description = $modules{$name};
	&mod_desc($form,$description); 
	if ($notes) { &write_to_statusbar($notes);
	} else {	&write_to_statusbar(""); }
}

# ----------- callbacks for modules... ----------------------

sub get_form { return $form; }
sub get_vars { return ($form,$tempdir,\%defined_tt_entries,\%uid_tt_entries); }
sub get_modules { return \%modules; }
sub get_help { return $helpfile; }
sub get_description { return $modules{$_[0]}; }
sub get_lib { return $libdir; }
sub get_debug { return $debug; }
sub get_rest_type {
	my ($what) = @_;
	my $ret;
	my $tv = $form->get_widget('treeview_modules')->get_model;
	$tv->foreach(sub {
 		my (undef,undef,$child_iter) = @_; 	 	 
		my $module = $tv->get($child_iter,0); 	# najprej vse razsiritve vseh modulov
 			my $description = $modules{$module}; 
 			foreach my $desc (split/\n/,$description) {	
 				if ($desc) { 
 					my @spec = split/:/,$desc; 
 					$spec[0] =~ s/ *$//g;
 					$spec[1] =~ s/ *$//g;
 					$spec[1] =~ s/^ *//g;
 					if ($spec[1] eq $what) {		
 						$spec[0] =~ s/ restrictions//g;
						$ret = $spec[0];
						return $spec[0];	# Subject / Class / Room / Tuple
 					}
 				}
 			}
		return 0;
 	});
	return 0;
}

# -------------------------I/O -----------------------------
sub save_file {		# shrani datoteko
	my ($filename) = @_;
	my $encoding = $form->get_widget('entry_encoding')->get_text;
# napolni $filename
	my $output = &generateXML($filename,$form,\%defined_tt_entries,\%uid_tt_entries);
 	if (-e $filename) { system("mv $filename $filename.bak"); }
	my @file = split/\./,$filename;
	my $type = $file[$#file];
	if ($type eq 'gz') {
		open (XML,"|iconv -f utf8 -t $encoding | gzip > $filename");
		print XML $output;
		close XML;	
	} elsif ($type eq 'xml') {
		open (XML,"|iconv -f utf8 -t $encoding -o $filename");
		print XML $output;
		close XML;	
	}	
	$form->get_widget('window_main')->set_title("G-Tablix - $filename");
	&write_to_statusbar("File $filename successfuly saved.");
}
sub import {
	my ($filename, $what) = @_;
  if (!-r $filename) {
  		&check("Couldn't open file\n$filename\nCheck full path and permissions",'error');
  } else {
	my $errors;
	my $encoding = $form->get_widget('entry_encoding')->get_text;
	$what =~ tr/A-Z/a-z/;
	if ($what eq "classes") { $what = "classs"; }
	my $tw = $form->get_widget("treeview_$what")->get_model;	
	open (WHAT,"<$filename");
	while (my $line = <WHAT>) {
		chop $line;
		my @what = split/\t/,$line;
		if (defined $what[0]) {
			if ($what eq "teachers") { $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  Errors while importing:\n"."$errors\n";
		&error($message,"Notice");
	} else {
		&write_to_statusbar("File $filename successfuly imported.");
	}
  }
}
sub export {
	my ($filename, $what) = @_;
	$what =~ tr/A-Z/a-z/;
	my $encoding = $form->get_widget('entry_encoding')->get_text;
	if ($what eq "classes") { $what = "classs"; }
	if (-e $filename) { system("mv $filename $filename.bak"); }
	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 ($who) { print WHAT "$who\t$for\t$how\n"; }
		return 0;
	} );
	close WHAT;	
	&write_to_statusbar("Sucessfully exported to file $filename.");
}
# ---------------------- drugo -------------------------------
sub build_uids {
	my %tts = %defined_tt_entries;
	%uid_tt_entries = ();
	my $temp; my $counter = 0;
	foreach my $who (sort(values(%tts))) {
		if ($temp eq $who) {	
			my $when = &get_when($who);
			if ($when) {
				
			}
	 	}
	}
}

sub get_when {
	my ($who) = @_;
	while ((my $key, my $value) = each %defined_tt_entries) {
		if ($value eq $who) {
			delete $defined_tt_entries{$key};
			return $key;
		}
	}
	return 0;
}

sub check_module {
	my ($what) = @_;
	my $tv_m = $form->get_widget('treeview_modules')->get_model;
	my $state = 0;
	$tv_m->foreach(sub {
		my (undef,undef,$child_iter) = @_; 	 
		my ($name,$active) = $tv_m->get($child_iter,0,3);
 			my $description = $modules{$name}; 
 			foreach my $desc (split/\n/,$description) {	
 				if ($desc) { 
 					my @spec = split/:/,$desc; 
 					$spec[0] =~ s/ *$//g;
 					$spec[1] =~ s/ *$//g;
 					$spec[1] =~ s/^ *//g;
					foreach my $s (split/ /,$spec[1]) {
 						if ($s eq $what) {		
	 						if ($active) { $state = 1; }
							return 1; 
 						}
					}
 				}
 			}
		return 0;		 
	});
	return $state;
}
