###########################################################################
#
# OggVorbisPlug.pm -- A plugin for Ogg Vorbis audio files
#
# Original code by Christy Kuo
#
# A component of the Greenstone digital library software
# from the New Zealand Digital Library Project at the 
# University of Waikato, New Zealand.
#
# Copyright 1999-2004 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.
#
###########################################################################

package OggVorbisPlug;


use UnknownPlug;
use Ogg::Vorbis::Header::PurePerl;

use strict;
no strict 'refs'; # allow filehandles to be variables and viceversa

sub BEGIN {
    @OggVorbisPlug::ISA = ('UnknownPlug');
}


my $arguments =
    [ { 'name' => "process_exp",
	'desc' => "{BasPlug.process_exp}",
	'type' => "string",
	'deft' => &get_default_process_exp(),
	'reqd' => "no" },
      { 'name' => "add_technical_metadata",
	'desc' => "{OggVorbisPlug.add_technical_metadata}",
	'type' => "flag",
	'deft' => "" } ];

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


# This plugin processes exported Ogg Vorbis files with the suffix ".ogg"
sub get_default_process_exp
{
    return q^(?i)(\.ogg)$^;
}


sub new
{
    my ($class) = shift(@_);
    my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
    push(@$pluginlist, $class);
    
    if(defined $arguments){ push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});}
    if(defined $options) { push(@{$hashArgOptLists->{"OptList"}},$options)};
    
    my $self = new UnknownPlug($pluginlist, $inputargs, $hashArgOptLists);
    
    return bless $self, $class;
}


sub read
{
    my $self = shift (@_);
    my ($pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;

    my $outhandle = $self->{'outhandle'};

    #check process and block exps, smart block, etc
    my ($block_status,$filename) = $self->read_block(@_);    
    return $block_status if ((!defined $block_status) || ($block_status==0));

     # Report that we're processing the file
    print STDERR "<Processing n='$file' p='OggVorbisPlug'>\n" if ($gli);
    print $outhandle "OggVorbisPlug: processing $file\n"
  	if ($self->{'verbosity'}) > 1;
    
    # file is just the name of the file (need to get rid off any leading directory names)
    $file =~ s/^.*[\/\\]//;

    # create a new index document
    my $doc_obj = new doc ($filename, "indexed_doc");
    if ($processor->{'OIDtype'} =~ /^(assigned|dirname)$/) {
	$doc_obj->set_OIDtype ($processor->{'OIDtype'}, $processor->{'OIDmetadata'});
    }
    else {
	$doc_obj->set_OIDtype ("incremental");    # this is done to avoid hashing content of file
    }
    my $section = $doc_obj->get_top_section();
    
    # replace spaces in filename with %20 in url for metadata entry
    my $url = $file;
    $url =~ s/ /%20/g;
    # Source (filename) to be consistent with other plugins
    $doc_obj->add_metadata ($section, "Source", $url);

    # Extract metadata
    my $ogg = Ogg::Vorbis::Header::PurePerl->new($filename);

    # Comments added to the file
    foreach my $key ($ogg->comment_tags())
    {
	# Convert key to title case
	my $keytc = uc(substr($key, 0, 1)) . substr($key, 1, length($key));
	foreach my $value ($ogg->comment($key))
	{
	    if (defined $value && $value ne "") {
		$doc_obj->add_metadata($section, $keytc, $value);
	    }
	}
    }

    # Technical data (optional)
    if ($self->{'add_technical_metadata'}) {
	foreach my $key (keys %{$ogg->info})
	{
	    # Convert key to title case
	    my $keytc = uc(substr($key, 0, 1)) . substr($key, 1, length($key));
	    my $value = $ogg->info->{$key};
	    if (defined $value && $value ne "") {
		$doc_obj->add_metadata($section, $keytc, $value);
	    }
	}
    }

    # srclink
    $doc_obj->add_metadata ($section, "FileFormat", "OggVorbis");
    $doc_obj->add_metadata ($section, "srclink", "<a href=\"_httpprefix_/collect/[collection]/index/assoc/[assocfilepath]/[Source]\">");
    $doc_obj->add_metadata ($section, "/srclink", "</a>");
    # srcicon (need to include "iogg.gif" in the greenstone images directory
    $doc_obj->add_metadata ($section, "srcicon", "<img src=\"_httpprefix_/images/iogg.gif\" title=\"Download\" border=0>");

    # Add the actual file as an associated file
    $doc_obj->associate_file($filename, $file, "VORBIS", $section);

    # Create an empty text string so we don't break downstream plugins 
     my $text = &gsprintf::lookup_string("{BasPlug.dummy_text}",1);

    # include any metadata passed in from previous plugins
    $self->extra_metadata ($doc_obj, $section, $metadata);

    # do plugin specific processing of doc_obj
    return undef unless defined ($self->process (\$text, $pluginfo, $base_dir, $file, $metadata, $doc_obj));

    # do any automatic metadata extraction
    $self->auto_extract_metadata($doc_obj);

    # add an OID
    $doc_obj->set_OID();
    $doc_obj->add_utf8_text($section, $text);

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

    $self->{'num_processed'}++;
    return 1;
}


1;
