###########################################################################
#
# ConvertToPlug.pm -- plugin that inherits from BasPlug
#
# 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 plugin is inherited by such plugins as WordPlug, PPTPlug, PSPlug, RTFPlug 
# and PDFPlug. It facilitates the conversion of these document types to either 
# HTML, Text or auto (allow user to choose which format to convert to).
# It works by dynamically inheriting BasPlug and base on the plugin type in
# secondary_plugins to devide which format to 'convert_to'. If the argument is 
# not present, the default is to inherit auto.
package ConvertToPlug;

use BasPlug;
use ghtml;
use HTMLPlug;
use TEXTPlug;
use PagedImgPlug;

#use strict;
#no strict 'refs'; # allow filehandles to be variables and viceversa

sub BEGIN {
    @ConvertToPlug::ISA = ('BasPlug');
}

my $convert_to_list =
    [ {	'name' => "auto",
	'desc' => "{ConvertToPlug.convert_to.auto}" },
      {	'name' => "html",
	'desc' => "{ConvertToPlug.convert_to.html}" },
      {	'name' => "text",
	'desc' => "{ConvertToPlug.convert_to.text}" },
      { 'name' => "pagedimg_jpg",
	'desc' => "{ConvertToPlug.convert_to.pagedimg_jpg}"},
      { 'name' => "pagedimg_gif",
	'desc' => "{ConvertToPlug.convert_to.pagedimg_gif}"},
      { 'name' => "pagedimg_png",
	'desc' => "{ConvertToPlug.convert_to.pagedimg_png}"}, 
      ];

my $arguments =
    [ { 'name' => "convert_to",
	'desc' => "{ConvertToPlug.convert_to}",
	'type' => "enum",
	'reqd' => "yes",
	'list' => $convert_to_list, 
	'deft' => "html" },
      { 'name' => "title_sub",
	'desc' => "{HTMLPlug.title_sub}",
	'type' => "string", 
	#'type' => "regexp",
	'deft' => "" },
      { 'name' => "use_strings",
	'desc' => "{ConvertToPlug.use_strings}",
	'type' => "flag",
	'reqd' => "no" },
      { 'name' => "extract_keyphrases",
	'desc' => "{BasPlug.extract_keyphrases}",
	'type' => "flag",
	'reqd' => "no",
	'hiddengli' => "yes" },
      { 'name' => "extract_keyphrase_options",
	'desc' => "{BasPlug.extract_keyphrase_options}",
	'type' => "string",
	'reqd' => "no",
	'hiddengli' => "yes" } ];

my $options = { 'name'     => "ConvertToPlug",
		'desc'     => "{ConvertToPlug.desc}",
		'abstract' => "yes",
		'inherits' => "yes",
		'args'     => $arguments };

sub findType
{
    my ($inputargs) = @_;
    my ($convert_to_type,$windows_scripting);
    $conver_to_type = "html";
    $windows_scripting = "false";
    for(my $intCounter = 0; $intCounter < scalar(@{$inputargs}) ; $intCounter++)
    {
	if($inputargs->[$intCounter] eq "-convert_to")
	{
	    if($inputargs->[$intCounter+1] eq "auto" || $inputargs->[$intCounter+1] =~ /pagedimg.*/i || $inputargs->[$intCounter+1] eq "text" || $inputargs->[$intCounter+1] eq "html")
	    # if the setting is "auto" then refer to html for now
	    #if($inputargs->[$intCounter+1] =~ /pagedimg.*/i || $inputargs->[$intCounter+1] eq "text" || $inputargs->[$intCounter+1] eq "html")
	    {
		$conver_to_type = $inputargs->[$intCounter+1];
	    }
	}
	if ($inputargs->[$intCounter] eq "-windows_scripting")
	{
	    $windows_scripting = "true";
	}
    }
    return ($conver_to_type,$windows_scripting);
}

sub load_secondary_plugins
{
    my $self = shift (@_);
    my ($class,$input_args,$hashArgOptLists) = @_;

    my @convert_to_list = split(",",$self->{'convert_to'});
    $secondary_plugins = {};

    foreach my $convert_to (@convert_to_list) {
	# load in "convert_to" plugin package
	my $plugin_class = $convert_to."Plug";
	my $plugin_package = $plugin_class.".pm";

	require $plugin_package;

	# call its constructor with extra options that we've worked out!
	my $arglist = $input_args->{$plugin_class};
	my $secondary_plugin = new $plugin_class([],$arglist, $hashArgOptLists);
	$secondary_plugins->{$plugin_class} = $secondary_plugin;
    }
    $self->{'secondary_plugins'} = $secondary_plugins;
}

sub new {
    my ($class) = shift (@_);
    my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
    push(@$pluginlist, $class);
    my $classPluginName = (defined $pluginlist->[0]) ? $pluginlist->[0] : $class;
    my ($strConvertTo,$blnWindowsScripting) = findType($inputargs);

    if(defined $arguments){ push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});}
    if(defined $options) { push(@{$hashArgOptLists->{"OptList"}},$options)};

    if ($classPluginName eq "PDFPlug" && $strConvertTo eq "text" && 
	$ENV{'GSDLOS'} =~ /^windows$/i) {
	print STDERR "Windows does not support pdf to text. PDFs will be converted to HTML instead\n";
	$strConvertTo = "html";
    }
    my $self = {};
    my $plugin_class ="";
    if ($classPluginName eq "WordPlug" && $blnWindowsScripting eq "true" &&
	$ENV{'GSDLOS'} =~ /^windows$/i) {
	$plugin_class = "StructuredHTML"."Plug";
    } elsif ($strConvertTo =~ /pagedimg.*/i){
	$plugin_class = "PagedImg"."Plug";
    } else {
	$plugin_class = uc($strConvertTo)."Plug";
    }
    
    my $plugin_package = $plugin_class.".pm";
    require $plugin_package;

    #call its constructor with extra options that we've worked out!
    my $arglist = $plugin_options->{$plugin_class};
    $self = (defined $hashArgOptLists)? new $plugin_class($pluginlist,$inputargs,$hashArgOptLists): new $plugin_class($pluginlist,$inputargs);

    if ($plugin_class eq "StructuredHTMLPlug") {
	$self->{'convert_to'} = "StructuredHTML";
	$self->{'convert_to_ext'} = "html";
#	my $structhtml_options = [];
#	push(@$structhtml_options,"-metadata_fields","Title,GENERATOR");
#	$secondary_plugin_options->{'StructuredHTMLPlug'} = $structhtml_options;
    }
    elsif ($strConvertTo eq "text")
    {
	$self->{'convert_to'} = "TEXT";
	$self->{'convert_to_ext'} = "txt";
#	my $text_options = [];
#	push(@$text_options,"-metadata_fields","Title,GENERATOR");
#	$secondary_plugin_options->{'TextPlug'} = $text_options;
    }
    elsif ($strConvertTo =~ /pagedimg.*/i){
	$self->{'convert_to'} = "PagedImg";
	my $convert_to_ext = $strConvertTo;
	$convert_to_ext =~ s/.*\_(.*)/$1/i;
	if ($convert_to_ext eq "gif"){
	    $self->{'convert_to_ext'} = "gif";
	} elsif ($convert_to_ext eq "jpg"){
	    $self->{'convert_to_ext'} = "jpg";
	} elsif ($convert_to_ext eq "png") {
	    $self->{'convert_to_ext'} = "png";
	}
#   	my $pagedimg_options = [];
#	push(@$pagedimg_options,"-metadata_fields","Title,GENERATOR");
#	$secondary_plugin_options->{'PagedImgPlug'} = $pagedimg_options;
    } else {
	# HTML or auto
	$self = (defined $hashArgOptLists)? new HTMLPlug($pluginlist,$inputargs,$hashArgOptLists): new HTMLPlug($pluginlist,$inputargs);
	$self->{'convert_to'} = "HTML";
	$self->{'convert_to_ext'} = "html";
#	my $html_options = [];
#	push(@$html_options,"-rename_assoc_files","1");
#	push(@$html_options,"-metadata_fields","Title,GENERATOR");
#	$secondary_plugin_options->{'HTMLPlug'} = $html_options;
    }
    return bless $self, $class;
}


sub init {
    my $self = shift (@_);
    my ($verbosity, $outhandle, $failhandle) = @_;

    $self->SUPER::init($verbosity,$outhandle,$failhandle);

    my $secondary_plugins =  $self->{'secondary_plugins'};

    foreach my $plug_name (keys %$secondary_plugins) {
	my $plugin = $secondary_plugins->{$plug_name};
	$plugin->init($verbosity,$outhandle,$failhandle);
    }
}

sub deinit {
    # called only once, after all plugin passes have been done

    my ($self) = @_;

    my $secondary_plugins =  $self->{'secondary_plugins'};

    foreach my $plug_name (keys %$secondary_plugins) {
	my $plugin = $secondary_plugins->{$plug_name};
	$plugin->deinit();
    }
}

sub convert_post_process
{
    # by default do no post processing
    return;
}


# Run conversion utility on the input file.  
#
# The conversion takes place in a collection specific 'tmp' directory so 
# that we don't accidentally damage the input.
#
# The desired output type is indicated by $output_ext.  This is usually
# something like "html" or "word", but can be "best" (or the empty string)
# to indicate that the conversion utility should do the best it can.
sub tmp_area_convert_file {
    my $self = shift (@_);
    my ($output_ext, $input_filename, $textref) = @_;
    
    my $outhandle = $self->{'outhandle'};
    my $convert_to = $self->{'convert_to'};
    my $failhandle = $self->{'failhandle'};
    my $convert_to_ext = $self->{'convert_to_ext'};
    
    # softlink to collection tmp dir
    my $tmp_dirname 
	= &util::filename_cat($ENV{'GSDLCOLLECTDIR'}, "tmp");
    &util::mk_dir($tmp_dirname) if (!-e $tmp_dirname);

    # derive tmp filename from input filename
    my ($tailname, $dirname, $suffix)
	= &File::Basename::fileparse($input_filename, "\\.[^\\.]+\$");

    # Remove any white space from filename -- no risk of name collision, and
    # makes later conversion by utils simpler. Leave spaces in path...
    # tidy up the filename with space, dot, hyphen between
    $tailname =~ s/\s+//g; 
    $tailname =~ s/\.+//g;
    $tailname =~ s/\-+//g;
    $suffix = lc($suffix);
    my $tmp_filename = &util::filename_cat($tmp_dirname, "$tailname$suffix");
    &util::soft_link($input_filename, $tmp_filename);
    my $verbosity = $self->{'verbosity'};
    if ($verbosity > 0) {
	print $outhandle "Converting $tailname$suffix to $convert_to format\n";
    }

    my $errlog = &util::filename_cat($tmp_dirname, "err.log");
    
    # Execute the conversion command and get the type of the result,
    # making sure the converter gives us the appropriate output type
    my $output_type="";
    if ($convert_to =~ m/PagedImg/i) {
	$output_type = lc($convert_to)."_".lc($convert_to_ext);
    } else {
	$output_type = lc($convert_to);
    }

    my $cmd = "perl -S gsConvert.pl -verbose $verbosity ";
    if (defined $self->{'convert_options'}) {
	$cmd .= $self->{'convert_options'} . " ";
    }
    if ($self->{'use_strings'}) {
      $cmd .= "-use_strings ";
    }
    $cmd .= "-errlog \"$errlog\" -output $output_type \"$tmp_filename\"";

    $output_type = `$cmd`;

    # remove symbolic link to original file
    &util::rm($tmp_filename);

    # Check STDERR here
    chomp $output_type;
    if ($output_type eq "fail") {
	print $outhandle "Could not convert $tailname$suffix to $convert_to format\n";
	print $failhandle "$tailname$suffix: " . ref($self) . " failed to convert to $convert_to\n";
	$self->{'num_not_processed'} ++;
	if (-s "$errlog") {
	    open(ERRLOG, "$errlog");
	    while (<ERRLOG>) {
		print $outhandle "$_";
	    }
	    print $outhandle "\n";
	    close ERRLOG;
	}
	&util::rm("$errlog") if (-e "$errlog");
	return "";
    }

    # store the *actual* output type and return the output filename
    # it's possible we requested conversion to html, but only to text succeeded
    #$self->{'convert_to_ext'} = $output_type;
    if ($output_type =~ /html/i) {
	$self->{'converted_to'} = "HTML";
    } elsif ($output_type =~ /te?xt/i) {
	$self->{'converted_to'} = "TEXT";
    } elsif ($output_type =~ /item/i){
	$self->{'converted_to'} = "PagedImg";
    }
    
    my $output_filename = $tmp_filename;
    if ($output_type =~ /item/i) {
	# running under windows
	if ($ENV{'GSDLOS'} =~ /^windows$/i) {
	    $output_filename = $tmp_dirname . "\\$tailname\\" . $tailname . ".$output_type";
	} else {
	    $output_filename = $tmp_dirname . "\/$tailname\/" . $tailname . ".$output_type";
	}
    } else {
	$output_filename =~ s/$suffix$/.$output_type/;
    }
    return $output_filename;
}


# Remove collection specific tmp directory and all its contents.
sub cleanup_tmp_area {
    my $self = shift (@_);

    my $tmp_dirname 
	= &util::filename_cat($ENV{'GSDLCOLLECTDIR'}, "tmp");
    &util::rm_r($tmp_dirname);
    &util::mk_dir($tmp_dirname);
}

# Override BasPlug read
# We don't want to get language encoding stuff until after we've converted
# our file to either TEXT or HTML or PagedImage.
sub read {
    my $self = shift (@_);
    my ($pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
    #if ($self->is_recursive()) {
    #   die "BasPlug::read function must be implemented in sub-class for recursive plugins\n";
    # }

    my $outhandle = $self->{'outhandle'};
    
    my ($block_status,$filename) = $self->read_block(@_);
    return $block_status if ((!defined $block_status) || ($block_status==0));
    $file = $self->read_tidy_file($file);
    
    my $output_ext = $self->{'convert_to_ext'};
    my $conv_filename = "";
    $conv_filename = $self->tmp_area_convert_file($output_ext, $filename);

    if ("$conv_filename" eq "") {return 0;} # allows continue on errors
    if (! -e "$conv_filename") {return 0;} # allows continue on errors
    $self->{'conv_filename'} = $conv_filename;
    $self->convert_post_process($conv_filename);
    
    my $secondary_plugins =  $self->{'secondary_plugins'};
    my $num_secondary_plugins = scalar(keys %$secondary_plugins);

    if ($num_secondary_plugins == 0) {
	print $outhandle "Warning: No secondary plugin to use in conversion.  Skipping $file\n";
	return 0; # effectively block it
    }

    my @plugin_names = keys %$secondary_plugins;
    my $plugin_name = shift @plugin_names;
	
    if ($num_secondary_plugins > 1) {
	print $outhandle "Warning: Multiple secondary plugins not supported yet!  Choosing $plugin_name\n.";
    }
   
    my $secondary_plugin = $secondary_plugins->{$plugin_name};

    # note: metadata is not carried on to the next level
    my ($rv,$doc_obj) 
	= $secondary_plugin->read_into_doc_obj ($pluginfo,"", $conv_filename, 
						$metadata, $processor, $maxdocs, $total_count,
						$gli);

    if ((!defined $rv) || ($rv<1)) {
	# wasn't processed
	return $rv;
    }
    
    # Override previous gsdlsourcefilename set by secondary plugin
    my $collect_file = &util::filename_within_collection($filename);
    my $collect_conv_file = &util::filename_within_collection($conv_filename);
    $doc_obj->set_source_filename ($collect_file); 
    $doc_obj->set_converted_filename($collect_conv_file);

    my ($filemeta) = $file =~ /([^\\\/]+)$/;
    $doc_obj->set_utf8_metadata_element($doc_obj->get_top_section(), "Source", &ghtml::dmsafe($filemeta));
    $doc_obj->set_utf8_metadata_element($doc_obj->get_top_section(), "Plugin", "$self->{'plugin_type'}");
    $doc_obj->set_utf8_metadata_element($doc_obj->get_top_section(), "FileSize", (-s $filename));

    # do plugin specific processing of doc_obj
    unless (defined ($self->process(undef, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli))) {
	print STDERR "<ProcessingError n='$file'>\n" if ($gli);
	return -1;
    }
    # do any automatic metadata extraction
    $self->auto_extract_metadata ($doc_obj);
    # add an OID
    $doc_obj->set_OID();
    # process the document
    $processor->process($doc_obj);
    ##$self->cleanup_tmp_area();

    $self->{'num_processed'} ++;

    return 1;
}


# do plugin specific processing of doc_obj for doc_ext type
sub process_type {
    my $self = shift (@_);
    my ($doc_ext, $base_dir, $file, $doc_obj) = @_;
    
    # associate original file with doc object
    my $cursection = $doc_obj->get_top_section();
    my $filename = &util::filename_cat($base_dir, $file);
    $doc_obj->associate_file($filename, "doc.$doc_ext", undef, $cursection);

    my $file_type;

    if ($doc_ext eq "doc") {
    	$file_type = "Word";
    } elsif ($doc_ext eq "xls") {
	$file_type = "Excel";
    } elsif ($doc_ext eq "ppt") {
	$file_type = "PPT"; 
    } elsif ($doc_ext eq "pdf") {
	$file_type = "PDF"; 
    } elsif ($doc_ext eq "rtf") {
	$file_type = "RTF";
    } elsif ($doc_ext eq "ps") {
	$file_type = "PS";
    }

    my $file_format = $file_type || "unknown";

    # We use set instead of add here because we only want one value
    $doc_obj->set_utf8_metadata_element($cursection, "FileFormat", $file_format);

    my $doclink = "<a href=\"_httpcollection_/index/assoc/[archivedir]/doc.$doc_ext\">";
    $doc_obj->add_utf8_metadata ($cursection, "srclink",  $doclink); 
    $doc_obj->add_utf8_metadata ($cursection, "srcicon",  "_icon".$doc_ext."_"); 
    $doc_obj->add_utf8_metadata ($cursection, "/srclink", "</a>"); 

    return 1;
}

1;







