###########################################################################
#
# CSVPlug.pm -- A plugin for metadata in comma-separated value format
#
# A component of the Greenstone digital library software
# from the New Zealand Digital Library Project at the 
# University of Waikato, New Zealand.
#
# Copyright 2006 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 CSVPlug;


use BasPlug;
use strict;


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


my $arguments =
    [ { 'name' => "block_exp",
	'desc' => "{BasPlug.block_exp}",
	'type' => "regexp",
	'reqd' => "no",
	'deft' => &get_default_block_exp() } ];


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


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 BasPlug($pluginlist, $inputargs, $hashArgOptLists);

    return bless $self, $class;
}


# Not used, just here to prevent a warning
sub get_default_process_exp
{
    return q^(?i)\.csv$^;
}


# We don't want any other plugins to see .csv files
sub get_default_block_exp
{
    return q^(?i)\.csv$^;
}


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

    # Read metadata from CSV files
    my $filename = &util::filename_cat($base_dir, $file);
    if ($filename !~ /\.csv$/ || !-f $filename) {
	return undef;
    }
    print STDERR "\n<Processing n='$file' p='CSVPlug'>\n" if ($gli);
    print STDERR "CSVPlug: processing $file\n" if ($self->{'verbosity'}) > 1;

    # Read the CSV file to get the metadata
    my $csv_file_content;
    open(CSV_FILE, "$filename");
    my $csv_file_reader = new multiread();
    $csv_file_reader->set_handle('CSVPlug::CSV_FILE');
    $csv_file_reader->read_file(\$csv_file_content);
    close(CSV_FILE);

    # Split the file into lines and read the first line (contains the metadata names)
    $csv_file_content =~ s/\n//g;
    my @csv_file_lines = split(/\r/, $csv_file_content);
    my $csv_file_field_line = shift(@csv_file_lines);
    my @csv_file_fields = split(/\,/, $csv_file_field_line);
    for (my $i = 0; $i < scalar(@csv_file_fields); $i++) {
	# Remove any spaces from the field names
	$csv_file_fields[$i] =~ s/ //g;
    }

    # Read each line of the file and assign the metadata appropriately
    foreach my $csv_line (@csv_file_lines) {
	# Ignore lines containing only whitespace
	next if ($csv_line =~ /^\s*$/);

	# Build a hash of metadata name to metadata value for this line
	my %csv_line_metadata;
	my $i = 0;
	$csv_line .= ",";  # To make the regular expressions simpler
	while ($csv_line ne "") {
	    # Metadata values containing commas are quoted
	    if ($csv_line =~ s/^\"(.*?)\"\,//) {
		# Only bother with non-empty values
		if ($1 ne "" && defined($csv_file_fields[$i])) {
		    $csv_line_metadata{$csv_file_fields[$i]} = $1;
		}
	    }
	    # Normal comma-separated case
	    elsif ($csv_line =~ s/^(.*?)\,//) {
		# Only bother with non-empty values
		if ($1 ne "" && defined($csv_file_fields[$i])) {
		    $csv_line_metadata{$csv_file_fields[$i]} = $1;
		}
	    }
	    # The line must be formatted incorrectly
	    else {
		print STDERR "Error: Badly formatted CSV line: $csv_line.\n";
		last;
	    }

	    $i++;
	}

	# We can't associate any metadata without knowing the file to associate it with
	my $csv_line_filename = $csv_line_metadata{"Filename"};
	if (!defined($csv_line_filename)) {
	    print STDERR "Error: No Filename metadata in CSV line: $csv_line\n";
	    next;
	}
	delete $csv_line_metadata{"Filename"};

 	# Associate the metadata now
 	$extrametadata->{$csv_line_filename} = \%csv_line_metadata;
 	push(@$extrametakeys, $csv_line_filename);
    }
}


1;
