#!/usr/bin/perl

###########################################################################
#
# fromsearch.pl
#
# A component of the Greenstone digital library software
# from the New Zealand Digital Library Project at the 
# University of Waikato, New Zealand.
#
# Copyright (C) 1999 New Zealand Digital Library Project
#
# 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., 675 Mass Ave, Cambridge, MA 02139, USA.
#
###########################################################################

# This code generates a single page version of the Greenstone Interface
# Translation Agency when accessed from a search of the Macro Collection.
# This allows users to correct mistakes made in translations.

BEGIN {
    die "GSDLHOME not set\n" unless defined $ENV{'GSDLHOME'};
    unshift (@INC, "$ENV{'GSDLHOME'}/perllib");
}

use parsargv;
use util;
use Cwd;
use File::Basename;
use GDBM_File;
use CGI;
#require utf8;
#use unicode;

&main(@ARGV);

sub main {
    
    $macroname = shift(@_);
    $language = shift(@_);
    $baselanguage = shift(@_);
    
    $dir = util::filename_cat($ENV{'GSDLHOME'},"tmp","lang","gdbmfiles");

    #finds the macroname in the dbfiles
    my $db1_blang = util::filename_cat($dir,$baselanguage.".db");
    my $db1_lang  = util::filename_cat($dir,language.".db");
    my $db2_blang = util::filename_cat($dir,$baselanguage."2.db");
    my $db2_lang  = util::filename_cat($dir,language."2.db");

    my ($formhash) = &db_db_diffs ($db1_blang, $db1_lang, $macroname);
    my ($formhash2) = &db_db_diffs($db2_blang, $db2_lang, $macroname);

    #puts results of above calls into one hash
    $formhash = &combine_hashes($formhash,$formhash2);

    #generates form using the one macro and macrotext from above
    &generate_form($formhash, $language, $baselanguage);

}
#loops through each hash which is passed to it, appending each value
#to a new third hash. Returns the third hash as result.
sub combine_hashes {
    
    my ($hash1, $hash2) = @_;
    my %combined = ();

    foreach $key (sort (keys %$hash1)) {
	$combined{$key} = $hash1->{$key};
    }
    foreach $key (sort (keys %$hash2)) {
	$combined{$key} = $hash2->{$key};
    }

    return (\%combined);

}

sub db_db_diffs
{
    my ($db_one, $db_two, $macroname) = @_;

    my %db1hash = ();
    my %db2hash = ();
    my %months = ("Jan",1,"Feb",2,"Mar",3,"Apr",4,"May",5,"Jun",6,
		  "Jul",7,"Aug",8,"Sep",9,"Oct",10,"Nov",11,"Dec",12);
    
    # this hash holds the database entries that are in 
    # english.db but not in $filename.db
    my %diffhash = ();

    #ties the hash to database so when you read from hash it fetches from external
    #database and when you set hash it writes to external database
    tie(%db1hash, "GDBM_File", $db_one, GDBM_READER, 0640);
    tie(%db2hash, "GDBM_File", $db_two, GDBM_READER, 0640);

    #the key is the name of the macro
    foreach $key (sort keys(%db1hash)) {

	#the macro has to be in one of the dbfiles so just want to keep scrolling
	#through until we hit it...
	if ($key eq $macroname) {
	    $foreigntext = $db2hash{$key};
	    if ($foreigntext =~ m/\#\# /) {
		$foreigntext = $& if ($foreigntext =~ m/\"(.|^)*\"/);
	    }
	    else {
		$foreigntext =~ s/^.*\n//;
		$foreigntext =~ s/.*\{//;
		$foreigntext =~ s/\}\Z//;
		$foreigntext =~ s/\n\Z//;
	    }
	    #puts the macroname as a key with the array containing the macro text in
	    #the base language and in the translation language
	    $diffhash{$key} = [$db1hash{$key}, $foreigntext];
	}
    }
    untie %db1hash;
    untie %db2hash;

    return \%diffhash;    
} 

sub generate_form
{
    my ($formhash) = shift(@_);
    my $language = shift(@_);
    my $baselanguage = shift(@_);
    my $fs_fname = util::filename_cat($ENV{'GSDLHOME'},"tmp","lang",
				      "package_forms", "$lang", "fromsearch.lang");

    open (FILE, ">$fs_fname") or die "Unable to open $fs_fname: $!\n";
    # common gateway interface for writing the stuff to the web
    my $query = new CGI;
    
    #used to indicate whether or not content of table has been generated
    my $processed = "false";
    
    #prints table headings and passes hidden data for page
    print FILE ($query->hidden(-name=>"hiddenlanguage",-default=>"$language"),
		$query->hidden(-name=>"baselanguage",-default=>"$baselanguage"),
		"</center><table cellpadding=\"10\">\n",
		"<tr><td><strong><center>".uc ($baselanguage)."</strong></center></td>\n",
		"<td><strong><center>". uc ($language)."</strong></center></td></tr>\n");
    

    foreach $key (keys(%$formhash)) {

	#changes to indicate hash did contain data and table content will be created
	$processed = "true";
	
	#gets the base language text from the hash
	my $text = $formhash->{$key}[0];
	my $keyname = $key;
	$keyname  =~ s/_/\\_/g;
	# strip off the date
	$text =~ s/.*//;
	$text =~ s/(\[l=.*\])//;
	
        # must take care of image macros single and multiple line ones
	$text =~ s/(\<br\>\#\#.*\#\#\s*\<br\>).*/$1/g;
	
	# format the text for displaying in the browser
	$text =~ s/[\{\}]//g unless($text =~ m/\#\# /);
	$text =~ s/(\A\n)//;
	$text =~ s/(\n\Z)//;
	
	#gets the translation language text from the hash
	my $default = $formhash->{$key}[1];    
	
        # so that when it is an image only get the text to translate not coding stuff aswell
	if ($text =~ m/\#\# (^|.)*/) {
	    if ($& =~ m/".*"/) {
		#prints to file two text fields, the left contains the base language text
		#and cannot be modified, the right contains the translation language text
		#to be modified and submitted
		print FILE ("<tr><td>",

			   $query->textfield(-name=>"whocares",
					     -default=>"$&",
					     -size=>50,
					     -readonly=>1),
			   "</td><td>",
			   $query->hidden(-name=>"$keyname",-default=>"$`"));
		print FILE ($query->textfield(-name=>"$keyname",
					     -default=>"$default",
					     -size=>50));
		print FILE ($query->hidden(-name=>"$keyname",-default=>"$'"),
			   "</td></tr>\n");
	    }
	}
	#else have a normal macro of form _this_
	elsif ($text =~ m/\S+/) {
		$text =~ s/\s+/ /g;
		
		$text =~ s/<p>/<p>\n/g;
		$text =~ s/<br>/<br>\n/g;
		$text =~ s/<\/td>/<\/td>\n/g;

		#see how long the macro text is to determine whether to use a text
		#field or a text area
		my @words = split(/ /, $text);
		my $words = scalar(@words);
		my $rows = sprintf("%.0f", $words/5);
		print FILE ("<tr><td>\n");
		#prints to file two text regions, the left contains the base language text
		#and cannot be modified, the right contains the translation language text
		#to be modified and submitted
		if ($rows > 1) {
		    print FILE ($query->textarea(-name=>"whocares",
						-rows=>$rows * 2,
						-default=>"$text",
						-columns=>50,
						-readonly=>1), 
			       "</td><td>\n",
			       $query->textarea(-name=>"$keyname",
						-rows=>$rows * 2,
						-default=>"$default",
						-columns=>50), 
			       "<br></td></tr>\n");  
		}
		else {
		    print FILE ($query->textfield(-name=>"whocares",
						 -default=>"$text",
						 -size=>50,
						 -readonly=>1),
			       "</td><td>\n",
			       $query->textfield(-name=>"$keyname",
						 -default=>"$default",
						 -size=>50),
			       "<br></td></tr>\n");
		}
	    }
    }

    #catch where hash is empty and print appropriate error message for user
    if ($processed eq "false") {
	print FILE ("<tr><td colspan=2 align=center>",
		    "An error occurred while processing your request\n<br>",
		    "</td></tr>")
	}

    #finishes table and adds a SUBMIT CHANGES option on the end
    print FILE ("</table><br><center>\n",
	       "<table><tr><td align=left width=\"50%\">",
	       $query->reset("RESET FORM"),
	       "</td><td align=right width=\"50%\">",
	       $query->submit($pageno, "_textsubmit_"),
	       "</td></tr><tr><td width=\"50%\"></td><td align=right width=\"50%\">",
	       "<br> _textsubmittext_ \n",
	       "</td></tr></table>");

    # adds the CGI area just written to the array of CGI areas
    push (@queries, $query);
    
    return $query;
}

