#!/usr/bin/perl -w
#
#     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
# 		contributions: Tomaz Solc
# 		19.12.2004, 30.1.2005, 27.2.2005

use strict;

# --------- check these for your system...
my $version = "0.0.8-1";

use lib "./modules";
use lib "/usr/lib";

my $libdir = $0;
	$libdir =~ s/\/gtablix//;
if ($libdir eq '/usr/bin') { $libdir = '/usr/lib'; }

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

use encoding 'utf8';
use POSIX;
use Locale::gettext;
use Glib qw(TRUE FALSE);
use Gtk2 '-init';    
use Gtk2::GladeXML;
use Gtk2::SimpleList; 

# then we load other modules
use gtablix::gui;
use gtablix::check;
use gtablix::xml;
use gtablix::modinfo;
use gtablix::helpers;
use gtablix::plot;
use gtablix::ttview;
use gtablix::wizard;
use gtablix::ttedit;	
use gtablix::tvs;

# settings 
my $docdir;
my $picdir;
if ($libdir eq '/usr/lib') {
	$picdir = '/usr/share/gtablix';
	$docdir = '/usr/share/doc/gtablix';
} else {
	$picdir = $libdir.'/modules/pixmaps';
	$docdir = $libdir.'/doc';
	&check_locale_dirs;	
	bindtextdomain('gtablix',$libdir.'/po');
	$libdir = $libdir.'/modules';
}

# locales ---------------------
my $setlocale = "";
foreach my $l (@ARGV) {
	my @l = split/=/,$l;
	if ($l[0] eq '-lang') {
		if (defined $l[1]) { 
			$setlocale = $l[1]; 
		}
	}
}

my $locale = setlocale(LC_MESSAGES,$setlocale);
if (!defined $locale) { 
	$locale = setlocale(LC_MESSAGES,find_locale($setlocale)); 
} elsif ($locale eq 'C') {
	$locale = setlocale(LC_MESSAGES,find_locale('en')); 
}
#bind_textdomain_codeset('gtablix','utf-8');
textdomain('gtablix');

#------------------------
# other settings
my $form = Gtk2::GladeXML->new("$libdir/gtablix/gtablix.glade",undef,'gtablix');
	$form->signal_autoconnect_from_package('main');
my %modules; my %defined_tt_entries; my %uid_tt_entries;
my $helpfile = "$docdir/".gettext("help.html");
my $wizardfile = "$docdir/".gettext("wizard.help");
my $faqfile = "$docdir/".gettext("faq.txt");

&init_stuff;
Gtk2->main;

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

# then we setup variables callback
sub get_version { return $version; }
sub get_doc { return $docdir; }
sub get_form { return $form; }
sub get_picdir { return $picdir; }
sub get_vars { return ($form,undef,\%defined_tt_entries,\%uid_tt_entries); }
sub get_modules { return \%modules; }
sub get_help { return ($helpfile,$wizardfile,$faqfile); }
sub get_description { return $modules{$_[0]}; }
sub get_locale { return $locale; }
# --------- gui handlers -----------------------------------
sub get_debug {
	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 check_locale_dirs {
	my @locales = split/\n/,readpipe("ls -1 $libdir/po/*.mo");
	foreach my $l (@locales) {
		my @lang = split/\//,$l;
		my $lang = (split/\./,$lang[$#lang])[1];
		if (!-e "$libdir/po/$lang") {
			print "Directory for language: $lang doesn't exists. Creating...\n";
			system("mkdir $libdir/po/$lang");
		}
		if (!-e "$libdir/po/$lang/LC_MESSAGES") {
			print "Directory for language messages: $lang doesn't exists. Creating...\n";
			system("mkdir $libdir/po/$lang/LC_MESSAGES");
		}
		if (!-e "$libdir/po/$lang/LC_MESSAGES/gtablix.mo") {
			print "File for language: $lang doesn't exists. Creating...\n";
			system("cp $l $libdir/po/$lang/LC_MESSAGES/gtablix.mo");
		}
	}
}
sub find_locale {		# find first matching locale from system install
	my ($locale) = @_;
	my @locales = readpipe('locale -a');
	foreach my $l (@locales) {
	 	my @l = split/\./,$l;
		if ($l[0] eq $locale) {
	 		return $l;
	 	} else {
			my @c = split/\_/,$l[0];
			if ($c[0] eq $locale) {
		 		return $l;
	 		}
		}
	}
	return $locale;
}
sub get_temp {
#	my $form = &get_form;
	my $tempdir = $form->get_widget('entry_temp')->get_text;
	if ($tempdir eq "") { $tempdir = "/tmp/gtablix"; }
	if (!-e $tempdir) { mkdir("$tempdir"); }
	return $tempdir;
}
sub load_modules { 		# Load accesible modules and descriptions into "modules" clist.
#	my ($form) = @_;
	my $path = $form->get_widget('entry_modpath')->get_text;
# some recomended values...
	my %values = (	'placecapability.so' => 40,
						'sametime.so' => 20,
						'timeplace.so' => 20,
						'student_freemorning.so' => 5,
						'student_walk.so' => 5,
						'student_holes.so' => 6,
						'teacher_freemorning.so' => 5,
						'teacher_holes.so' => 5,						
						'student_perday.so' => 2,
						'teacher_perday.so' => 2					
						);
	if (!-d $path) {
		&check(gettext("The modules path is not a directory.\nTablix modules will not work."),'error');
	} elsif (!-r $path) {
		&check(gettext("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; 
	 			my $val = $values{$mod};
					if (!defined $val) { $val = 0; }
				my $active = 0;
				if ($mod eq 'timeplace.so') { $active = 1; }
				$tv_m->set($row,0,$mod,1,$val,2,0,3,$active,4,"");
				$modules{$mod} = readpipe("tablix_modinfo $mod");
	 		}
	 	}
	}
}

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(""); }
}

# -------------------------I/O -----------------------------
sub save_file {		# shrani datoteko
	my ($filename,$how) = @_;
	my $encoding = $form->get_widget('entry_encoding')->get_text;
# napolni $filename
	# how: loose / strict
	my $output = &generateXML($filename,$form,\%defined_tt_entries,\%uid_tt_entries,$how);
 	if (-e $filename) { system("mv -f $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(gettext("File")." $filename ".gettext("successfuly saved."));
}
sub import {
	my ($filename, $what) = @_;
 if (!-r $filename) {
  		&check(gettext("Couldn't open file")."\n$filename\n".
			 gettext("Check full path and permissions"),'error');
  } 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]) {
			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  ".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 @file = split/\./,$filename;
	my $type = pop(@file);
	if ($type eq 'gz') {
		$filename = join('.',@file);
	}
	$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 (!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);
}
# ---------------------- 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;
}
# ----------- callbacks for modules... ----------------------

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;
}


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;
}
