###########################################################################
#
# PDFPlug.pm -- reasonably with-it pdf plugin
# 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-2001 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.
#
###########################################################################
use strict;
no strict 'refs'; # so we can use a var for filehandles (eg STDERR)

package PDFPlug;

use ConvertToPlug;
use unicode;

@PDFPlug::ISA = ('ConvertToPlug');

my $arguments =
    [ { 'name' => "process_exp",
	'desc' => "{BasPlug.process_exp}",
	'type' => "regexp",
	'deft' => &get_default_process_exp(),
	'reqd' => "no" },
      { 'name' => "block_exp",
	'desc' => "{BasPlug.block_exp}",
	'type' => "regexp",
	'deft' => &get_default_block_exp() },
      { 'name' => "noimages",
	'desc' => "{PDFPlug.noimages}",
	'type' => "flag" },
      { 'name' => "complex",
	'desc' => "{PDFPlug.complex}",
	'type' => "flag" },
      { 'name' => "nohidden",
	'desc' => "{PDFPlug.nohidden}",
	'type' => "flag" },
      { 'name' => "zoom",
	'desc' => "{PDFPlug.zoom}",
	'deft' => "2",
	'range' => "1,3", # actually the range is 0.5-3 
	'type' => "int" },
      { 'name' => "use_sections",
	'desc' => "{PDFPlug.use_sections}",
	'type' => "flag" } ];

my $options = { 'name'     => "PDFPlug",
		'desc'     => "{PDFPlug.desc}",
		'abstract' => "no",
		'inherits' => "yes",
		'args'     => $arguments };

sub new {
    my $class = shift (@_);

    my ($noimages, $complex, $zoom, $use_sections, $nohidden);

    my @args=@_;

    if (!parsargv::parse(\@_, 
			 q^noimages^, \$noimages,
			 q^complex^, \$complex,
			 q^zoom/\d+/2^, \$zoom,
			 q^nohidden^, \$nohidden,
			 q^use_sections^, \$use_sections,
			 "allow_extra_options")) {

	my $self = new ConvertToPlug($class, @_);
	my $outhandle=$self->{'outhandle'};
	print $outhandle "\nIncorrect options passed to PDFPlug, check your collect.cfg configuration file\n";
	$self->print_txt_usage("");  # Use default resource bundle
	exit 1;
    }


    if ($use_sections) {
	push (@args, "-description_tags");
    }

    # following title_sub removes "Page 1" added by pdftohtml, and a leading
    # "1", which is often the page number at the top of the page. Bad Luck
    # if your document title actually starts with "1 " - is there a better way?

    my $self = new ConvertToPlug ($class, @args, "-title_sub", '^(Page\s+\d+)?(\s*1\s+)?');
    $self->{'plugin_type'} = "PDFPlug";
    if ($use_sections) {
	$self->{'use_sections'}=1;
    }

    # 14-05-02 To allow for proper inheritance of arguments - John Thompson
    my $option_list = $self->{'option_list'};
    push( @{$option_list}, $options );

    # these are passed through to gsConvert.pl by ConvertToPlug.pm
    $self->{'convert_options'} = "-pdf_zoom $zoom";
    $self->{'convert_options'} .= " -pdf_complex" if $complex;
    $self->{'convert_options'} .= " -pdf_nohidden" if $nohidden;
    $self->{'convert_options'} .= " -pdf_ignore_images" if $noimages;

    # pdftohtml will always produce html files encoded as utf-8
    if ($self->{'input_encoding'} eq "auto") {
	$self->{'input_encoding'} = "utf8";
	$self->{'extract_language'} = 1;
    }

    return bless $self, $class;
}

sub get_default_process_exp {
    my $self = shift (@_);

    return q^(?i)\.pdf$^;
}

# so we don't inherit HTMLPlug's block exp...
sub get_default_block_exp {
    return "";
}
    

# do plugin specific processing of doc_obj for HTML type
sub process {
    my $self = shift (@_);
    my $outhandle=$self->{'outhandle'};

    my $textref=$_[0];

    if ($self->{'use_sections'}
	&& $self->{'converted_to'} eq "HTML") {

	print $outhandle "PDFPlug: Calculating sections...\n";

	# we have "<a name=1></a>" etc for each page
	my @sections = split('<a name=', $$textref);

	if (scalar (@sections) == 1) { #only one section - no split!
	    print $outhandle "PDFPlug: warning - no sections found\n";
	} else {
	    shift @sections; # don't need HTML header, etc
	}

	# handle first section specially for title? Or all use first 100...
	
	my $title = $sections[0];
	$title =~ s/^\d+>//; # specific for pdftohtml...
	$title =~ s/<\/([^>]+)><\1>//g; # (eg) </b><b> - no space
	$title =~ s/<[^>]*>/ /g;
	$title =~ s/(?:&nbsp;|\xc2\xa0)/ /g; # utf-8 for nbsp...
	$title =~ s/^\s+//s;
	$title =~ s/\s+$//;
	$title =~ s/\s+/ /gs;
	$title =~ s/^$self->{'title_sub'}// if ($self->{'title_sub'});
	$title =~ s/^\s+//s; # in case title_sub introduced any...
	$title = substr ($title, 0, 100);
	$title =~ s/\s\S*$/.../;

	my $top_section;
	if (scalar (@sections) == 1) { # no sections found
	    $top_section=$sections[0];
	    @sections=();
	} else {
	    $top_section = "<!--<Section>\n<Metadata name=\"Title\">$title</Metadata>\n-->\n <!--</Section>-->\n";
	}

	# add metadata per section...
	foreach my $section (@sections) {
	    $section =~ s@^(\d+)></a>@@; # leftover from split expression...

	    $title = $1; # Greenstone does magic if sections are titled digits
	    if (! defined($title) ) {
		print STDERR "no title: $section\n";
	    }
	    my $newsection = "<!-- from PDFPlug -->\n<!-- <Section>\n";
	    $newsection .= "<Metadata name=\"Title\">" . $title
		. "</Metadata>\n--><p>\n";
	    $newsection .= $section;
	    $newsection .= "<!--</Section>-->\n";
	    $section = $newsection;
	}

	$$textref=join('', ($top_section, @sections));
    }

    # turn any high bytes that aren't valid utf-8 into utf-8.
    unicode::ensure_utf8($textref);

    print $outhandle "PDFPlug: passing $_[3] on to $self->{'converted_to'}Plug\n"
	if $self->{'verbosity'} > 1;

    # tell htmlplug to extract these metadata fields from the HEAD META fields
    $self->{'metadata_fields'} .= ",date,author<Creator>";

    my $result = ConvertToPlug::process_type($self,"pdf",@_);

    my $doc_obj = pop(@_);

    # fix up the extracted date metadata to be in Greenstone date format,
    # and fix the capitalisation of 'date'
    my $cursection = $doc_obj->get_top_section();

    foreach my $datemeta (@{$doc_obj->get_metadata($cursection, "date")}) {
	$doc_obj->delete_metadata($cursection, "date", $datemeta);

	# We're just interested in the date bit, not the time
	# some pdf creators (eg "Acrobat 5.0 Scan Plug-in for Windows")
	# set a /CreationDate, and set /ModDate to 000000000. pdftohtml
	# extracts the ModDate, so it is 0...
	$datemeta =~ /(\d+)-(\d+)-(\d+)/;
	my ($year, $month, $day) = ($1,$2,$3);
	if (defined($year) && defined($month) && defined($day)) {
	    if ($year == 0) {next}
	    if ($year < 100) {$year += 1900} # just to be safe
	    if ($month =~ /^\d$/) {$month="0$month"} # single digit
	    if ($day =~ /^\d$/) {$day="0$day"} # single digit
	    my $date="$year$month$day";
	    $doc_obj->add_utf8_metadata($cursection, "Date", $date);
	}
    }

    # Add NumPages metadata (we have "<a name=1>" etc for each page)
    my @pages = ($$textref =~ /\<a name=\d+\>/ig);
    $doc_obj->add_utf8_metadata($cursection, "NumPages", scalar(@pages));

    return $result;
}

1;
