###########################################################################
#
# GBBPlug.pm -- plugin for processing gb encoded html books
# 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.
#
###########################################################################

# creates multi-level document from document containing 
# <<TOC>> level tags. Metadata for each section is taken from any
# other tags on the same line as the <<TOC>>. e.g. <<Title>>xxxx<</Title>>
# sets Title metadata.

# Everything else between TOC tags is expected to be simple html
# and is treated accordingly.

# Imput files are expected to be GB encoded and have .gbb file extension

# a file with the same name as the gbb file but a .jpg extension is
# taken as the cover image

package GBBPlug;

use BasPlug;
use sorttools;
use util;
use unicode;
use cnseg;
use gb;


sub BEGIN {
    @ISA = ('BasPlug');
}

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

    return bless $self, $class;
}

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

    return 0; # this is not a recursive plugin
}


# return number of files processed, undef if can't process
# Note that $base_dir might be "" and that $file might 
# include directories
sub read {
    my $self = shift (@_);
    my ($pluginfo, $base_dir, $file, $metadata, $processor) = @_;

    my $filename = &util::filename_cat($base_dir, $file);
    my $absdir = $filename;
    $absdir =~ s/[^\/\\]*$//;

    return 0 if ($filename =~ /\.jpg$/i);
    return undef unless ($filename =~ /\.gbb$/i && (-e $filename));

    print STDERR "GBBPlug: processing $filename\n" if $processor->{'verbosity'};

    # create a new document
    my $doc_obj = new doc ($file, "indexed_doc");
    open (FILE, $filename) || die "GBBPlug::read - ERROR: can't open $filename\n";

    my $cursection = $doc_obj->get_top_section();

    # add the cover image
    my $coverimage = $filename;
    $coverimage =~ s/\.gbb/\.jpg/i;
    $doc_obj->associate_file($coverimage, "cover.jpg", "image/jpeg");

    my $text = "";
    my $line = "";
    my $title = "";
    while (defined ($line = <FILE>)) {
	$text .= $line;
    }

    # convert to unicode
    $text = &unicode::unicode2utf8(&gb::gb2unicode($text));
    # segment the Chinese words
    $text = &cnseg::segment($text);

    # we'll use the worthless alarm thingy to temporarily replace 
    # '\n' so we'd better check it doesn't occur naturally
    if ($text =~ /\a/) {
	print STDERR "GBBPlug::read - 'WARNING '\a' character occurs in text!!\n";
    }

    # remove line breaks
    $text =~ s/\n/\a/g;

    # remove any leading rubbish
    $text =~ s/^.*?(<<TOC)/$1/i;
    
    my $curtoclevel = 1;
    my $firstsection = 1;
    my $toccount = 0;
    while (length ($text) > 0) {
	$text =~ s/^<<TOC(\d+)>>([^\a]*)\a(.*?)(<<TOC|\Z)/$4/i;
	my $toclevel = $1;
	my $metadata = $2;
	my $sectiontext = $3;

	if ($toclevel == 2) {
	    $toccount ++;
	}
	    
	
	# close any sections below the current level and
	# create a new section (special case for the firstsection)
	while (($curtoclevel > $toclevel) ||
	       (!$firstsection && $curtoclevel == $toclevel)) {
	    $cursection = $doc_obj->get_parent_section ($cursection);
	    $curtoclevel--;
	}
	if ($curtoclevel+1 < $toclevel) {
	    print STDERR "WARNING - jump in toc levels in $htmlfile " . 
		"from $curtoclevel to $toclevel\n";
	}
	while ($curtoclevel < $toclevel) {
	    $curtoclevel++;
	    $cursection = 
		$doc_obj->insert_section($doc_obj->get_end_child($cursection));
	}

	# sort out metadata
	while ($metadata =~ s/^.*?<<([^>]*)>>(.*?)<<[^>]*>>//) {
	    my $metakey = $1;
	    my $metavalue = $2;

	    if ($metavalue ne "" && $metakey ne "") {
		# make sure key fits in with gsdl naming scheme 
		$metakey =~ tr/[A-Z]/[a-z]/;
		$metakey = ucfirst ($metakey);
		$doc_obj->add_utf8_metadata ($cursection, $metakey, $metavalue);
	    }
	}


	# remove header rubbish
	$sectiontext =~ s/^.*?<body[^>]*>//i;

	# and any other unwanted tags
	$sectiontext =~ s/<(\/p|\/html|\/body)>//ig;

	# fix up the image links
	$sectiontext =~ s/(<img[^>]*?src\s*=\s*\"?)([^\">]+)(\"?[^>]*>)/
	    &replace_image_links($absdir, $doc_obj, $1, $2, $3)/ige;

	# put line breaks back in
	$sectiontext =~ s/\a/\n/g;

	# add the text
	$doc_obj->add_utf8_text($cursection, $sectiontext);

	$firstsection = 0;
    }

    # add OID
    $doc_obj->set_OID ();

    # process the document
    $processor->process($doc_obj);

    return 1; # processed the file
}

sub replace_image_links {

    my ($dir, $doc_obj, $front, $link, $back) = @_;

    my ($filename, $error);
    my $foundimage = 0;
    
    $link =~ s/\/\///;
    my ($imagetype) = $link =~ /([^\.]*)$/;
    $imagetype =~ tr/[A-Z]/[a-z]/;
    if ($imagetype eq "jpg") {$imagetype = "jpeg";}
    if ($imagetype !~ /^(jpeg|gif|png)$/) {
	print STDERR "GBHPlug: Warning - unknown image type ($imagetype)\n";
    }
    my ($imagefile) = $link =~ /([^\/]*)$/;
    my ($imagepath) = $link =~ /^[^\/]*(.*)$/;

    if (defined $imagepath && $imagepath =~ /\w/) {
	# relative link
	$filename = &util::filename_cat ($dir, $imagepath);
	if (-e $filename) {
	    $doc_obj->associate_file ($filename, $imagefile, "image/$imagetype");
	    $foundimage = 1;
	} else {
	    $error = "GBHPlug: Warning - couldn't find image file $imagefile in either $filename or";
	}
    }

    if (!$foundimage) {
	$filename = &util::filename_cat ($dir, $imagefile);
	if (-e $filename) {
	    $doc_obj->associate_file ($filename, $imagefile, "image/$imagetype");    
	    $foundimage = 1;
	} elsif (defined $error) {
	    print STDERR "$error $filename\n";
	} else {
	    print STDERR "GBHPlug: Warning - couldn't find image file $imagefile in $filename\n";
	}
    }

    if ($foundimage) {
	return "${front}_httpdocimg_/${imagefile}${back}";
    } else {
	return "";
    }
}

1;











