###########################################################################
#
# basebuildproc.pm -- 
# 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 document processor outputs a document for indexing (should be 
# implemented by subclass) and storing in gdbm database

package basebuildproc;

eval {require bytes};

use classify;
use doc;
use docproc;
use util;

BEGIN {
    @basebuildproc::ISA = ('docproc');
}

sub new()
  {
    my ($class, $collection, $source_dir, $build_dir, $keepold, $verbosity, $outhandle) = @_;
    my $self = new docproc ();

    # outhandle is where all the debugging info goes
    # output_handle is where the output of the plugins is piped
    # to (i.e. mg, gdbm etc.)
    $outhandle = STDERR unless defined $outhandle;

    $self->{'collection'} = $collection;
    $self->{'source_dir'} = $source_dir;
    $self->{'build_dir'}  = $build_dir;
    $self->{'keepold'}    = $keepold;
    $self->{'verbosity'}  = $verbosity;
    $self->{'outhandle'}  = $outhandle;

    $self->{'classifiers'} = [];
    $self->{'mode'} = "text";
    $self->{'assocdir'} = $build_dir;
    $self->{'dontgdbm'} = {};

    $self->{'index'} = "section:text";
    $self->{'indexexparr'} = [];

    my $found_num_data = 0;
    my $buildconfigfile = undef;

    if ($keepold) {
	# For incremental building need to seed num_docs etc from values
	# stored in build.cfg (if present)
      print STDERR "Keepold!\n";
	$buildconfigfile = &util::filename_cat($build_dir, "build.cfg");
      print STDERR "Build cfg: $buildconfigfile\n";
	if (-e $buildconfigfile) {
	    $found_num_data = 1;
	}
	else {
	    # try the index dir
	    $buildconfigfile = &util::filename_cat($ENV{'GSDLCOLLECTDIR'}, 
						   "index", "build.cfg");
            print STDERR "Index cfg: $buildconfigfile\n";
	    if (-e $buildconfigfile) {
		$found_num_data = 1;
	    }
	}

    }
    #else
    #  {
    #    print STDERR "Removeold!\n";
    #  }

    if ($found_num_data)
      {
        #print STDERR "Found_Num_Data!\n";
	my $buildcfg = &colcfg::read_build_cfg($buildconfigfile);
	$self->{'starting_num_docs'}     = $buildcfg->{'numdocs'};
        #print STDERR "- num_docs:     $self->{'starting_num_docs'}\n";
	$self->{'starting_num_sections'} = $buildcfg->{'numsections'};
        #print STDERR "- num_sections: $self->{'starting_num_sections'}\n";
	$self->{'starting_num_bytes'}    = $buildcfg->{'numbytes'};
        #print STDERR "- num_bytes:    $self->{'starting_num_bytes'}\n";
    }
    else
      {
        #print STDERR "NOT Found_Num_Data!\n";
        $self->{'starting_num_docs'}     = 0;
	$self->{'starting_num_sections'} = 0;
	$self->{'starting_num_bytes'}    = 0;
      }

    $self->{'output_handle'} = "STDOUT";
    $self->{'num_docs'}      = $self->{'starting_num_docs'};
    $self->{'num_sections'}  = $self->{'starting_num_sections'};
    $self->{'num_bytes'}     = $self->{'starting_num_bytes'};

    $self->{'num_processed_bytes'} = 0;
    $self->{'store_text'} = 1;

    # what level (section/document) the gdbm database - indexer intersection is
    $self->{'gdbm_level'} = "section";
    #used by browse interface
    $self->{'doclist'} = [];

    $self->{'indexing_text'} = 0;

    return bless $self, $class;

}

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

    $self->{'num_docs'}      = $self->{'starting_num_docs'};
    $self->{'num_sections'}  = $self->{'starting_num_sections'};
    $self->{'num_bytes'}     = $self->{'starting_num_bytes'};
    
    $self->{'num_processed_bytes'} = 0;
}

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

    $self->{'num_docs'}      = 0;
    $self->{'num_sections'}  = 0;
    $self->{'num_bytes'}     = 0;
    
    $self->{'num_processed_bytes'} = 0;
}

sub is_incremental_capable
{
    # By default we return 'no' as the answer
    # Safer to assume non-incremental to start with, and then override in
    # inherited classes that are.

    return 0;
}

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

    return $self->{'num_docs'};
}

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

    return $self->{'num_sections'};
}

# num_bytes is the actual number of bytes in the collection
# this is normally the same as what's processed during text compression
sub get_num_bytes {
    my $self = shift (@_);

    return $self->{'num_bytes'};
}

# num_processed_bytes is the number of bytes actually passed
# to mg for the current index
sub get_num_processed_bytes {
    my $self = shift (@_);

    return $self->{'num_processed_bytes'};
}

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

    $self->{'output_handle'} = $handle;
}


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

    $self->{'mode'} = $mode;
}

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

    return $self->{'mode'};
}

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

    $self->{'assocdir'} = $assocdir;
}

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

    $self->{'dontgdbm'} = $dontgdbm;
}

sub set_index {
    my $self = shift (@_);
    my ($index, $indexexparr) = @_;

    $self->{'index'} = $index;
    $self->{'indexexparr'} = $indexexparr if defined $indexexparr;
}

sub set_index_languages {
    my $self = shift (@_);
    my ($lang_meta, $langarr) = @_;
    $self->{'lang_meta'} = $lang_meta;
    $self->{'langarr'} = $langarr;
}

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

    return $self->{'index'};
}

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

    $self->{'classifiers'} = $classifiers;
}

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

    $self->{'indexing_text'} = $indexing_text;
}

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

    return $self->{'indexing_text'};
}

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

    $self->{'store_text'} = $store_text;
}
sub get_doc_list {
    my $self = shift(@_);
    
    return @{$self->{'doclist'}};
}

# the standard gdbm level is section, but you may want to change it to document
sub set_gdbm_level {
    my $self= shift (@_);
    my ($gdbm_level) = @_;

    $self->{'gdbm_level'} = $gdbm_level;
}

sub set_sections_index_document_metadata {
    my $self= shift (@_);
    my ($index_type) = @_;
    
    $self->{'sections_index_document_metadata'} = $index_type;
}
sub process {
    my $self = shift (@_);
    my $method = $self->{'mode'};

    $self->$method(@_);
}

sub infodb {
    my $self = shift (@_);
    my ($doc_obj, $filename) = @_;
    my $handle = $self->{'output_handle'};

    my $doctype = $doc_obj->get_doc_type();

    # only output this document if it is a "indexed_doc" or "info_doc" (GDBM database only) document
    return if ($doctype ne "indexed_doc" && $doctype ne "info_doc");

    my $archivedir = "";

    if (defined $filename)
    {
	# doc_obj derived directly from file

	my ($dir) = $filename =~ /^(.*?)(?:\/|\\)[^\/\\]*$/;
	$dir = "" unless defined $dir;
	$dir =~ s/\\/\//g;
	$dir =~ s/^\/+//;
	$dir =~ s/\/+$//;

	$archivedir = $dir;

	# resolve the final filenames of the files associated with this document
	$self->assoc_files ($doc_obj, $archivedir);
    }
    else
    {
	# doc_obj reconstructed from GDBM (has metadata, doc structure but no text)
	my $top_section = $doc_obj->get_top_section();
	$archivedir = $doc_obj->get_metadata_element($top_section,"archivedir");
    }


    #GRB: moved 1/06/2004 from GRB01062004
    #add this document to the browse structure
    push(@{$self->{'doclist'}},$doc_obj->get_OID()) 
	unless ($doctype eq "classification");

    # classify this document
    &classify::classify_doc ($self->{'classifiers'}, $doc_obj);
    #GRB: end of moved block

    # this is another document
    $self->{'num_docs'} += 1 unless ($doctype eq "classification");

    # is this a paged or a hierarchical document
    my ($thistype, $childtype) = $self->get_document_type ($doc_obj);

    my $section = $doc_obj->get_top_section ();
    my $doc_OID = $doc_obj->get_OID();
    my $first = 1;
    my $url = "";
    while (defined $section) {
	# update a few statistics
	$self->{'num_bytes'} += $doc_obj->get_text_length ($section);
	$self->{'num_sections'} += 1 unless ($doctype eq "classification");

	# output the section name
	if ($section eq "") { print $handle "[$doc_OID]\n"; }
	else { print $handle "[$doc_OID.$section]\n"; }

	# output the fact that this document is a document (unless doctype
	# has been set to something else from within a plugin
	my $dtype = $doc_obj->get_metadata_element ($section, "doctype");
	if (!defined $dtype || $dtype !~ /\w/) {
	    print $handle "<doctype>doc\n";
	}

	# Output whether this node contains text
	#
	# If doc_obj reconstructed from GDBM file then no need to 
	# explicitly add <hastxt> as this is preserved as metadata when
	# the GDBM file is loaded in

	if (defined $filename)
	{
	    # doc_obj derived directly from file
	    if ($doc_obj->get_text_length($section) > 0) {
		print $handle "<hastxt>1\n";
	    } else {
		print $handle "<hastxt>0\n";
	    }
	}

	# output all the section metadata
	my $metadata = $doc_obj->get_all_metadata ($section);
	foreach my $pair (@$metadata) {
	    my ($field, $value) = (@$pair);

	    if ($field ne "Identifier" && $field !~ /^gsdl/ && 
		defined $value && $value ne "") {	    

		# escape problematic stuff
		$value =~ s/\\/\\\\/g;
		$value =~ s/\n/\\n/g;
		$value =~ s/\r/\\r/g;
		if ($value =~ /-{70,}/) {
		    # if value contains 70 or more hyphens in a row we need
		    # to escape them to prevent txt2db from treating them
		    # as a separator
		    $value =~ s/-/&\#045;/gi;
		}

		# special case for URL metadata
		if ($field =~ /^URL$/i) {
                    $url .= "[$value]\n";
                    if ($section eq "") {$url .= "<section>$doc_OID\n";}
                    else {$url .= "<section>$doc_OID.$section\n";}
                    $url .= '-' x 70 . "\n";
		}

		if (!defined $self->{'dontgdbm'}->{$field}) {
		    print $handle "<$field>$value\n";
		}
	    }
	}


	# If doc_obj reconstructed from GDBM file then no need to 
	# explicitly add <archivedir> as this is preserved as metadata when
	# the GDBM file is loaded in

	if (defined $filename)
	{
	    # output archivedir if at top level
	    if ($section eq $doc_obj->get_top_section()) {
		print $handle "<archivedir>$archivedir\n";
	    }
	}

	# output document display type
	if ($first) {
	    print $handle "<thistype>$thistype\n";
	}


	if ($self->{'gdbm_level'} eq "document") {
	    # doc num is num_docs not num_sections
	    # output the matching document number
	    print $handle "<docnum>$self->{'num_docs'}\n";
            
	} else {
	    # output a list of children
	    my $children = $doc_obj->get_children ($section);
	    if (scalar(@$children) > 0) {
		print $handle "<childtype>$childtype\n";
		print $handle "<contains>";
		my $firstchild = 1;
		foreach my $child (@$children) {
		    print $handle ";" unless $firstchild;
		    $firstchild = 0;
		    if ($child =~ /^.*?\.(\d+)$/) {
			print $handle "\".$1";
		    } else {
			print $handle "\".$child";
		    }
#		if ($child eq "") { print $handle "$doc_OID"; }
#		elsif ($section eq "") { print $handle "$doc_OID.$child"; }
#		else { print $handle "$doc_OID.$section.$child"; }
		}
		print $handle "\n";
	    }
	    #output the matching doc number
	    print $handle "<docnum>$self->{'num_sections'}\n";
	    
	} 
	
	print $handle '-' x 70, "\n";

	
	# output a database entry for the document number
	if ($self->{'gdbm_level'} eq "document") {
	    print $handle "[$self->{'num_docs'}]\n";
	    print $handle "<section>$doc_OID\n";
	}
	else {
	    print $handle "[$self->{'num_sections'}]\n";
	    if ($section eq "") { print $handle "<section>$doc_OID\n"; }
	    else { print $handle "<section>$doc_OID.$section\n"; }
	}
	print $handle '-' x 70, "\n";
	
        # output entry for url
        if ($url ne "") {
            print $handle $url;
        }

	$first = 0;
	$section = $doc_obj->get_next_section($section);
	last if ($self->{'gdbm_level'} eq "document"); # if no sections wanted, only gdbm the docs
    }

    #GRB01062004: see code above moved from here
}


sub text {
    my $self = shift (@_);
    my ($doc_obj) = @_;
    
    my $handle = $self->{'outhandle'};
    print $handle "basebuildproc::text function must be implemented in sub classes\n";
    die "\n";
}

# should the document be indexed - according to the subcollection and language
# specification.
sub is_subcollection_doc {
    my $self = shift (@_);
    my ($doc_obj) = @_;
    
    my $indexed_doc = 1;
    foreach my $indexexp (@{$self->{'indexexparr'}}) {
	$indexed_doc = 0;
	my ($field, $exp, $options) = split /\//, $indexexp;
	if (defined ($field) && defined ($exp)) {
	    my ($bool) = $field =~ /^(.)/;
	    $field =~ s/^.// if $bool eq '!';
	    my @metadata_values;
	    if ($field =~ /^filename$/i) {
		push(@metadata_values, $doc_obj->get_source_filename());
	    }
	    else {
		@metadata_values = @{$doc_obj->get_metadata($doc_obj->get_top_section(), $field)};
	    }
	    next unless @metadata_values;
	    foreach my $metadata_value (@metadata_values) {
		if ($bool eq '!') {
		    if ($options =~ /^i$/i) {
			if ($metadata_value !~ /$exp/i) {$indexed_doc = 1; last;}
		    } else {
			if ($metadata_value !~ /$exp/) {$indexed_doc = 1; last;}
		    }
		} else {
		    if ($options =~ /^i$/i) {
			if ($metadata_value =~ /$exp/i) {$indexed_doc = 1; last;}
		    } else {
			if ($metadata_value =~ /$exp/) {$indexed_doc = 1; last;}
		    }
		}
	    }

	    last if ($indexed_doc == 1);
	}
    }
    
    # if this doc is so far in the sub collection, and we have lang info, 
    # now we check the languages to see if it matches
    if($indexed_doc && defined $self->{'lang_meta'}) {
	$indexed_doc = 0;
	my $field = $doc_obj->get_metadata_element($doc_obj->get_top_section(), $self->{'lang_meta'});
	if (defined $field) {
	    foreach my $lang (@{$self->{'langarr'}}) {
		my ($bool) = $lang =~ /^(.)/;
		if ($bool eq '!') {
		    $lang =~ s/^.//;
		    if ($field !~ /$lang/) {
			$indexed_doc = 1; last;
		    }
		} else {
		    if ($field =~ /$lang/) {
			$indexed_doc = 1; last;
		    }
		}
	    }
	} 
    }
    return $indexed_doc;
    
}

# use 'Paged' if document has no more than 2 levels
# and each section at second level has a number for
# Title metadata
# also use Paged if gsdlthistype metadata is set to Paged
sub get_document_type {
    my $self = shift (@_);
    my ($doc_obj) = @_;

    my $thistype = "VList";
    my $childtype = "VList";
    my $title;
    my @tmp = ();
    
    my $section = $doc_obj->get_top_section ();
    
    my $gsdlthistype = $doc_obj->get_metadata_element ($section, "gsdlthistype");
    if (defined $gsdlthistype) {
	if ($gsdlthistype eq "Paged") {
	    $childtype = "Paged";
	    if ($doc_obj->get_text_length ($doc_obj->get_top_section())) {
		$thistype = "Paged";
	    } else {
		$thistype = "Invisible";
	    }
	    
	    return ($thistype, $childtype);
	} elsif ($gsdlthistype eq "Hierarchy") {
	    return ($thistype, $childtype); # use VList, VList
	}
    }
    my $first = 1;
    while (defined $section) {
	@tmp = split /\./, $section;
	if (scalar(@tmp) > 1) {
	    return ($thistype, $childtype);
	}
	if (!$first) {
	    $title = $doc_obj->get_metadata_element ($section, "Title");
	    if (!defined $title || $title !~ /^\d+$/) {
		return ($thistype, $childtype);
	    }
	}
	$first = 0;
	$section = $doc_obj->get_next_section($section);
    }
    if ($doc_obj->get_text_length ($doc_obj->get_top_section())) {
	$thistype = "Paged";
    } else {
	$thistype = "Invisible";
    }
    $childtype = "Paged";
    return ($thistype, $childtype);
}

sub assoc_files() {
    my $self = shift (@_);
    my ($doc_obj, $archivedir) = @_;
    my ($afile);
    
    foreach my $assoc_file (@{$doc_obj->get_assoc_files()}) {
      #rint STDERR "Processing associated file - copy " . $assoc_file->[0] . " to " . $assoc_file->[1] . "\n";
	# if assoc file starts with a slash, we put it relative to the assoc
	# dir, otherwise it is relative to the HASH... directory
	if ($assoc_file->[1] =~ m@^[/\\]@) {
	    $afile = &util::filename_cat($self->{'assocdir'}, $assoc_file->[1]);
	} else {
	    $afile = &util::filename_cat($self->{'assocdir'}, $archivedir, $assoc_file->[1]);
	}
	&util::hard_link ($assoc_file->[0], $afile);
    }
}

