###########################################################################
#
# GenericList.pm -- A general and flexible list classifier with most of
#                   the abilities of AZCompactList, and better Unicode,
#                   metadata and sorting capabilities.
#
# A component of the Greenstone digital library software
# from the New Zealand Digital Library Project at the 
# University of Waikato, New Zealand.
#
# Author: Michael Dewsnip, NZDL Project, University of Waikato, NZ
#
# Copyright (C) 2005 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.
#
# TO DO: Remove punctuation from metadata values before sorting.
#
###########################################################################

package GenericList;


use BasClas;

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


sub BEGIN {
    @GenericList::ISA = ('BasClas');
}


my $arguments = 
    [ { 'name' => "metadata",
	'desc' => "{GenericList.metadata}",
	'type' => "metadata",
	'reqd' => "yes" },
      # The interesting options
      { 'name' => "always_bookshelf_last_level",
	'desc' => "{GenericList.always_bookshelf_last_level}",
	'type' => "flag" },
      { 'name' => "classify_sections",
	'desc' => "{GenericList.classify_sections}",
	'type' => "flag" },
      { 'name' => "partition_type_within_level",
	'desc' => "{GenericList.partition_type_within_level}",
	'type' => "string",
	'deft' => "none" },
      { 'name' => "partition_size_within_level",
	'desc' => "{GenericList.partition_size_within_level}",
	'type' => "string" },
      { 'name' => "sort_leaf_nodes_using",
	'desc' => "{GenericList.sort_leaf_nodes_using}",
	'type' => "metadata",
	'deft' => "Title" },
      { 'name' => "use_hlist_for",
	'desc' => "{GenericList.use_hlist_for}",
	'type' => "string" } ];

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


sub new
{
    my ($class) = shift(@_);
    my ($classifierslist, $inputargs, $hashArgOptLists) = @_;
    push(@$classifierslist, $class);

    if (defined $arguments) { push(@{$hashArgOptLists->{"ArgList"}}, @{$arguments}); }
    if (defined $options) { push(@{$hashArgOptLists->{"OptList"}}, $options); }

    my $self = (defined $hashArgOptLists) ? new BasClas($classifierslist, $inputargs, $hashArgOptLists) : new BasClas($classifierslist, $inputargs);
    $self->{'OIDlist'} = [];

    if ($self->{'info_only'}) {
	# don't worry about any options etc
	return bless $self, $class;
    }

    my $metadata = $self->{'metadata'};
    my $buttonname = $self->{'buttonname'};
    my $partition_type_within_level = $self->{'partition_type_within_level'};
    my $partition_size_within_level = $self->{'partition_size_within_level'};
    my $sort_leaf_nodes_using = $self->{'sort_leaf_nodes_using'};
    my $use_hlist_for = $self->{'use_hlist_for'};

    # The metadata elements to use (required)
    # print STDERR "Creating new GenericList for $metadata...\n";
    if (!$metadata) {
	die "Error: No metadata fields specified for GenericList.\n";
    }
    my @metalist = split(/\//, $metadata);
    $self->{'metalist'} = \@metalist;

    # The classifier button name
    if (!$buttonname) {
	# Default: the first metadata element specified
	my $firstmetagroupfirstelem = (split(/\;/, $metalist[0]))[0];
	$buttonname = $self->generate_title_from_metadata($firstmetagroupfirstelem);
    }
    $self->{'title'} = $buttonname;

    # Whether to group single items into a bookshelf (must be true for all metadata fields except the last)
    foreach my $metagroup (@metalist) {
	$self->{$metagroup . ".always_bookshelf"} = "t";
    }
    if (!$self->{'always_bookshelf_last_level'}) {
	# Default: leave leafnodes ungrouped (equivalent to AZCompactList -mingroup 2)
	my $lastmetagroup = $metalist[$#metalist];
	$self->{$lastmetagroup . ".always_bookshelf"} = "f";
    }

    # Whether to use an hlist or a vlist for each level in the hierarchy
    foreach my $metagroup (@metalist) {
	$self->{$metagroup . ".use_hlist"} = "f";
    }
    foreach my $metagroup (split(/\,/, $use_hlist_for)) {
	$self->{$metagroup . ".use_hlist"} = "t";
    }

    # How the items are grouped into partitions
    if (!$partition_type_within_level) {
	# Default: none
	$partition_type_within_level = "none";
    }
    $self->{"partition_type_within_level"} = $partition_type_within_level;

    # The number of items in each partition
    if (!$partition_size_within_level) {
	# Default: 20
	foreach my $metagroup (@metalist) {
	    $self->{$metagroup . ".partition_size_within_level"} = 20;
	}
    }
    else {
	my @partition_size_within_levellist = split(/\//, $partition_size_within_level);

	# Assign values based on the partition_size_within_level parameter
	foreach my $metagroup (@metalist) {
	    my $partition_size_within_levelelem = shift(@partition_size_within_levellist);
	    if (defined($partition_size_within_levelelem)) {
		$self->{$metagroup . ".partition_size_within_level"} = $partition_size_within_levelelem;
	    }
	    else {
		$self->{$metagroup . ".partition_size_within_level"} = $self->{$metalist[0] . ".partition_size_within_level"};
	    }
	}
    }

    # The metadata elements to use to sort the leaf nodes
    my @sort_leaf_nodes_usingmetalist = ( "Title" );
    if ($sort_leaf_nodes_using) {
	@sort_leaf_nodes_usingmetalist = split(/\|/, $sort_leaf_nodes_using);
    }
    $self->{'sort_leaf_nodes_usingmetalist'} = \@sort_leaf_nodes_usingmetalist;

    return bless $self, $class;
}


sub init
{
    # Nothing to do...
}


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

    my $doc_OID = $doc_obj->get_OID();

    if ($self->{'classify_sections'}) {
	my $section = $doc_obj->get_next_section($doc_obj->get_top_section());
	while (defined $section) {
	    $self->classify_section($doc_obj, $doc_OID . ".$section", $section);
	    $section = $doc_obj->get_next_section($section);
	}
    }
    else {
	$self->classify_section($doc_obj, $doc_OID, $doc_obj->get_top_section());
    }
}


sub classify_section
{
    my $self = shift(@_);
    my $doc_obj = shift(@_);
    my $doc_OID = shift(@_);
    my $section = shift(@_);

    my @metalist = @{$self->{'metalist'}};

    # Only classify the document if it has a value for one of the metadata elements in the first group
    foreach my $firstmetagroupelem (split(/\;/, $metalist[0])) {
	my $firstmetagroupelemvalue = $doc_obj->get_metadata_element($section, $firstmetagroupelem);
	if (defined($firstmetagroupelemvalue) && $firstmetagroupelemvalue ne "") {
	    push(@{$self->{'OIDlist'}}, $doc_OID);

	    # Create a hash for the metadata values of each metadata element we're interested in
	    my %metagroupsdone = ();
	    foreach my $metagroup (@metalist, @{$self->{'sort_leaf_nodes_usingmetalist'}}) {
		# Take care not to do a metadata group more than once
		unless ($metagroupsdone{$metagroup}) {
		    foreach my $metaelem (split(/\;/, $metagroup)) {
			my @metavalues = @{$doc_obj->get_metadata($section, $metaelem)};
			foreach my $metavalue (@metavalues) {
			    # Strip leading and trailing whitespace
			    $metavalue =~ s/^\s*//;
			    $metavalue =~ s/\s*$//;
			    push(@{$self->{$metagroup . ".list"}->{$doc_OID}}, $metavalue);
			}
			last if (@metavalues > 0);
		    }

		    $metagroupsdone{$metagroup} = 1;
		}
	    }

	    last;
	}
    }
}


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

    # The metadata elements to classify by
    my @metalist = @{$self->{'metalist'}};
    my $firstmetagroup = $metalist[0];

    # The OID values of the documents to include in the classification
    my @OIDlist = @{$self->{'OIDlist'}};

    # The root node of the classification hierarchy
    my $childtype = (($self->{$firstmetagroup . ".use_hlist"} eq "t") ? "HList" : "VList");
    my %classifyinfo = ( 'thistype' => "Invisible",
			 'childtype' => $childtype,
			 'Title' => $self->{'title'},
			 'contains' => [] );

    # Recursively create the classification hierarchy, one level for each metadata element
    &add_az_list($self, \@metalist, \@OIDlist, \%classifyinfo);
    return \%classifyinfo;
}


sub add_az_list
{
    my $self = shift(@_);
    my @metalist = @{shift(@_)};
    my @OIDlist = @{shift(@_)};
    my $classifyinfo = shift(@_);
    # print STDERR "\nAdding AZ list for " . $classifyinfo->{'Title'} . "\n";

    my $metagroup = $metalist[0];
    # print STDERR "Processing metadata group: " . $metagroup . "\n";
    # print STDERR "Number of OID values: " . @OIDlist . "\n";

    my %OIDtometavaluehash = %{$self->{$metagroup . ".list"}};

    # Create a mapping from metadata value to OID
    my %metavaluetoOIDhash = ();
    foreach my $OID (@OIDlist) {
	if ($OIDtometavaluehash{$OID}) {
	    my @metavalues = @{$OIDtometavaluehash{$OID}};
	    foreach my $metavalue (@metavalues) {
		push(@{$metavaluetoOIDhash{$metavalue}}, $OID);
	    }
	}
    }
    # print STDERR "Number of distinct values: " . scalar(keys %metavaluetoOIDhash) . "\n";

    # Partition the values (if necessary)
    my $partition_type_within_level = $self->{"partition_type_within_level"};
    if ($partition_type_within_level =~ /^per_letter$/i) {
	# Generate one hlist for each letter
	my @sortedmetavalues = sort(keys %metavaluetoOIDhash);
	my %metavaluetoOIDsubhash = ();

	my $lastpartition = &unicode::substr($sortedmetavalues[0], 0, 1);
	foreach my $metavalue (@sortedmetavalues) {
	    my $metavaluepartition = &unicode::substr($metavalue, 0, 1);

	    # Is this the start of a new partition?
	    if ($metavaluepartition ne $lastpartition) {
		&add_hlist_partition($self, \@metalist, $classifyinfo, $lastpartition, \%metavaluetoOIDsubhash);
		%metavaluetoOIDsubhash = ();
		$lastpartition = $metavaluepartition;
	    }

	    $metavaluetoOIDsubhash{$metavalue} = $metavaluetoOIDhash{$metavalue};	    
	}

	# Don't forget to add the last partition
	&add_hlist_partition($self, \@metalist, $classifyinfo, $lastpartition, \%metavaluetoOIDsubhash);

	# The partitions are stored in an HList
	$classifyinfo->{'childtype'} = "HList";
    }

    else {
	# Generate hlists of a certain size
	my $partition_size_within_level = $self->{$metagroup . ".partition_size_within_level"};
	if ($partition_type_within_level =~ /^constant_size$/i && scalar(keys %metavaluetoOIDhash) > $partition_size_within_level) {
	    my @sortedmetavalues = sort(keys %metavaluetoOIDhash);
	    my $itemsdone = 0;
	    my %metavaluetoOIDsubhash = ();
	    my $lastpartitionend = "";
	    my $partitionstart;
	    foreach my $metavalue (@sortedmetavalues) {
		$metavaluetoOIDsubhash{$metavalue} = $metavaluetoOIDhash{$metavalue};
		$itemsdone++;
		my $itemsinpartition = scalar(keys %metavaluetoOIDsubhash);

		# Is this the start of a new partition?
		if ($itemsinpartition == 1) {
		    $partitionstart = &generate_partition_start($metavalue, $lastpartitionend);
		}

		# Is this the end of the partition?
		if ($itemsinpartition == $partition_size_within_level || $itemsdone == @sortedmetavalues) {
		    my $partitionend = &generate_partition_end($metavalue, $partitionstart);
		    my $partitionname = $partitionstart;
		    if ($partitionend ne $partitionstart) {
			$partitionname = $partitionname . "-" . $partitionend;
		    }

		    &add_hlist_partition($self, \@metalist, $classifyinfo, $partitionname, \%metavaluetoOIDsubhash);
		    %metavaluetoOIDsubhash = ();
		    $lastpartitionend = $partitionend;
		}
	    }

	    # The partitions are stored in an HList
	    $classifyinfo->{'childtype'} = "HList";
	}

	# Otherwise just add all the values to a VList
	else {
	    &add_vlist($self, \@metalist, $classifyinfo, \%metavaluetoOIDhash);
	}
    }
}


sub unicode_length
{
    my $utf8string = shift(@_);

    my @unicodestring = @{&unicode::utf82unicode($utf8string)};
    return scalar(@unicodestring);
}


sub generate_partition_start
{
    my $metavalue = shift(@_);
    my $lastpartitionend = shift(@_);

    my $partitionstart = &unicode::substr($metavalue, 0, 1);
    if ($partitionstart le $lastpartitionend) {
	$partitionstart = &unicode::substr($metavalue, 0, 2);
	# Give up after three characters
	if ($partitionstart le $lastpartitionend) {
	    $partitionstart = &unicode::substr($metavalue, 0, 3);
	}
    }

    return $partitionstart;
}


sub generate_partition_end
{
    my $metavalue = shift(@_);
    my $partitionstart = shift(@_);

    my $partitionend = &unicode::substr($metavalue, 0, &unicode_length($partitionstart));
    if ($partitionend gt $partitionstart) {
	$partitionend = &unicode::substr($metavalue, 0, 1);
	if ($partitionend le $partitionstart) {
	    $partitionend = &unicode::substr($metavalue, 0, 2);
	    # Give up after three characters
	    if ($partitionend le $partitionstart) {
		$partitionend = &unicode::substr($metavalue, 0, 3);
	    }
	}
    }

    return $partitionend;
}


sub add_hlist_partition
{
    my $self = shift(@_);
    my @metalist = @{shift(@_)};
    my $classifyinfo = shift(@_);
    my $partitionname = shift(@_);
    my %metavaluetoOIDhash = %{shift(@_)};

    # Create an hlist partition
    my %subclassifyinfo = ( 'Title' => $partitionname,
			    'childtype' => "VList",
			    'contains' => [] );

    # Add the children to the hlist partition
    &add_vlist($self, \@metalist, \%subclassifyinfo, \%metavaluetoOIDhash);
    push(@{$classifyinfo->{'contains'}}, \%subclassifyinfo);
}


sub add_vlist
{
    my $self = shift(@_);
    my @metalist = @{shift(@_)};
    my $classifyinfo = shift(@_);
    my %metavaluetoOIDhash = %{shift(@_)};

    my $metagroup = shift(@metalist);

    # Create an entry in the vlist for each value
    foreach my $metavalue (sort(keys %metavaluetoOIDhash)) {
	my @OIDlist = @{$metavaluetoOIDhash{$metavalue}};

	# If there is only one item and 'always_bookshelf' is false, add the item to the list
	if (@OIDlist == 1 && $self->{$metagroup . ".always_bookshelf"} eq "f") {
	    push(@{$classifyinfo->{'contains'}}, { 'OID' => $OIDlist[0] });
	}

	# Otherwise create a sublist (bookshelf) for the metadata value
	else {
	    my %subclassifyinfo = ( 'Title' => $metavalue,
				    'childtype' => "VList",
				    'contains' => [] );

	    # If there are metadata elements remaining, recursively apply the process
	    if (@metalist > 0) {
		my $nextmetagroup = $metalist[0];
		my $childtype = (($self->{$nextmetagroup . ".use_hlist"} eq "t") ? "HList" : "VList");
		$subclassifyinfo{'childtype'} = $childtype;
		&add_az_list($self, \@metalist, \@OIDlist, \%subclassifyinfo);
	    }
	    # Otherwise just add the documents as children of this list
	    else {
		# Sort the leaf nodes by the metadata elements specified with -sort_leaf_nodes_using
		my @sort_leaf_nodes_usingmetalist = @{$self->{'sort_leaf_nodes_usingmetalist'}};
		foreach my $sort_leaf_nodes_usingmetaelem (reverse @sort_leaf_nodes_usingmetalist) {
		    my %OIDtometavaluehash = %{$self->{$sort_leaf_nodes_usingmetaelem . ".list"}};
		    # Force a stable sort (Perl 5.6's sort isn't stable)
		    # !! The [0] bits aren't ideal (multiple metadata values) !! 
		    @OIDlist = @OIDlist[ sort { $OIDtometavaluehash{$OIDlist[$a]}[0] cmp $OIDtometavaluehash{$OIDlist[$b]}[0] || $a <=> $b; } 0..$#OIDlist ];
		}

  		foreach my $OID (@OIDlist) {
  		    push(@{$subclassifyinfo{'contains'}}, { 'OID' => $OID });
  		}
	    }

	    # Add the sublist to the list
	    push(@{$classifyinfo->{'contains'}}, \%subclassifyinfo);
	}
    }
}


1;
