###########################################################################
#
# AZCompactList.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.
#
###########################################################################

# classifier plugin for sorting alphabetically
# options are:
# metadata=Metaname -- all documents with Metaname metadata
#                      will be included in list, list will be sorted
#                      by this element.
# title=Title       -- (optional) the title field for this classification.
#                      if not included title field will be Metaname. 
# mingroup=Num      -- (optional) the smallest value that will cause
#                      a group in the hierarchy to form.

package AZCompactList;

use sorttools;

sub new {
    my ($class, @options) = @_;

    my ($metaname, $title);
    my $mingroup = 2;

    foreach $option (@options) {
	if ($option =~ /^metadata=(.*)$/i) {
	    $metaname = $1;
	} elsif ($option =~ /^title=(.*)$/i) {
	    $title = $1;
	} elsif ($option =~ /^mingroup(size)?=(.*)$/i) {
	    $mingroup = $2;
	}
    }

    die "AZCompactList used with no metadata name to classify by\n"
	unless defined $metaname;
    $title = $metaname unless defined $title;

    return bless {
	'list'=>{}, 
	'listmetavalue'=>{}, 
	'reclassify'=>{},
	'reclassifylist'=>{},
	'metaname' => $metaname,
	'title' => $title,
	'mingroup' => $mingroup
	}, $class;
}

sub init 
{
    my $self = shift (@_);
    
    $self->{'list'} = {};
    $self->{'listmetavalue'} = {};
    $self->{'reclassify'} = {};
    $self->{'reclassifylist'} = {};
}

$tmp = 0;

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

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

    my $thissection = $doc_obj->get_top_section();
    my $metaname = $self->{'metaname'};

    my $metavalue = $doc_obj->get_metadata_element($thissection,$metaname);
    my $date = $doc_obj->get_metadata_element($thissection,"Date");

    # if this document doesn't contain the metadata element we're
    # sorting by we won't include it in this classification
    if (defined $metavalue && $metavalue =~ /\w/) 
    {
	my $formatted_metavalue = $metavalue;

	if ($self->{'metaname'} eq 'Creator') 
	{
	    &sorttools::format_string_name_english (\$formatted_metavalue);
	} 
	else 
	{
	    &sorttools::format_string_english (\$formatted_metavalue);
	}
	if (defined $self->{'list'}->{$doc_OID}) 
	{
	    print STDERR "WARNING: AZCompactList::classify called multiple times for $doc_OID\n";
	} 

	$self->{'list'}->{$doc_OID} = $formatted_metavalue;
	$self->{'listmetavalue'}->{$doc_OID} = $metavalue;
	$self->{'reclassify'}->{$doc_OID} = [$doc_obj,$date]
    }
}

sub reinit 
{
    my ($self,$classlist_ref) = @_;
    
    my %mtfreq = ();
    my @single_classlist = ();
    my @multiple_classlist = ();

    # find out how often each metavalue occurs
    map { $mtfreq{$self->{'listmetavalue'}->{$_}}++; } @$classlist_ref;

    # use this information to split the list: single metavalue/repeated value
    map
    { 
	my $metavalue = $self->{'listmetavalue'}->{$_};
	print "meta value = $metavalue; count = $mtfreq{$metavalue}\n";

	if ($mtfreq{$metavalue}>=$self->{'mingroup'})
	{
	    push(@multiple_classlist,$_); 
	} 
	else
	{
	    push(@single_classlist,$_); 
	    $self->{'reclassifylist'}->{$_} = $metavalue;
	}
    } @$classlist_ref;
    
    
    # Setup sub-classifiers for multiple list

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

    my $listname 
	= &util::filename_cat($ENV{'GSDLHOME'},"perllib/classify/List.pm");
    if (-e $listname) { require $listname; }
    else 
    { 
	die "TCCList ERROR - couldn't find classifier \"$listname\"\n"; 
    }

    my $metavalue;
    foreach $metavalue (keys %mtfreq)
    {
	if ($mtfreq{$metavalue}>=$self->{'mingroup'})
	{
	    my $listclassobj;
	    my $metaname  = $self->{'metaname'};
	    
	    eval ("\$listclassobj = new List(\"metadata=$metaname\", \"title=\$metavalue\", \"sort=Date\")");
	    die "$@" if $@;
	    
	    $listclassobj->init();

	    if (defined $metavalue && $metavalue =~ /\w/) 
	    {
		my $formatted_node = $metavalue;
		if ($self->{'metaname'} eq 'Creator') 
		{
		    &sorttools::format_string_name_english(\$formatted_node);
		} 
		else 
		{
		    &sorttools::format_string_english(\$formatted_node);
		}
		
		$self->{'classifiers'}->{$metavalue} 
		= { 'classifyobj'   => $listclassobj,
		    'formattednode' => $formatted_node };
	    }
	}
    }


    return (\@single_classlist,\@multiple_classlist);
}


sub reclassify 
{
    my ($self,$multiple_cl_ref) = @_;

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

    my $doc_OID;
    foreach $doc_OID (@$multiple_cl_ref) 
    {
        my $listclassobj;
        my $metavalue = $self->{'listmetavalue'}->{$doc_OID};
	
	# find metavalue in list of sub-classifiers
	my $found = 0;
	my $node_name;
	foreach $node_name (keys %{$self->{'classifiers'}}) 
	{
	    if ($metavalue =~ /^$node_name$/i) 
	    {
		my ($doc_obj,$date) = @{$self->{'reclassify'}->{$doc_OID}};

		$self->{'classifiers'}->{$node_name}->{'classifyobj'}
		      ->classify($doc_obj, $date);

		$found = 1;
		last;
	    }
	}

	if (!$found)
	{
	    print STDERR "Warning: AZCompactList::reclassify ";
	    print STDERR "could not find sub-node for $metavalue\n";
	}
    }
}



sub get_reclassify_info 
{
    my $self = shift (@_);
    
    my $node_name;
    foreach $node_name (keys %{$self->{'classifiers'}}) 
    {
        my $classifyinfo 
	    = $self->{'classifiers'}->{$node_name}->{'classifyobj'}
	        ->get_classify_info(1);
        $self->{'classifiers'}->{$node_name}->{'classifyinfo'} 
	    = $classifyinfo;
        $self->{'reclassifylist'}->{"CLASSIFY.$node_name"} 
	    = $self->{'classifiers'}->{$node_name}->{'formattednode'};
    }
}


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

    my @classlist = sort {$self->{'list'}->{$a} cmp $self->{'list'}->{$b};} keys %{$self->{'list'}};

    my ($single_cl_ref,$multiple_cl_ref) = $self->reinit(\@classlist);
    $self->reclassify($multiple_cl_ref);
    $self->get_reclassify_info();

    my @reclassified_classlist 
	= sort {$self->{'reclassifylist'}->{$a} cmp $self->{'reclassifylist'}->{$b};} keys %{$self->{'reclassifylist'}};

    return $self->splitlist (\@reclassified_classlist);
}

sub get_entry {
    my $self = shift (@_);
    my ($title, $childtype, $thistype) = @_;
    
    # organise into classification structure
    my %classifyinfo = ('childtype'=>$childtype,
			'Title'=>$title,
			'contains'=>[]);
    $classifyinfo{'thistype'} = $thistype 
	if defined $thistype && $thistype =~ /\w/;

    return \%classifyinfo;
}

# splitlist takes an ordered list of classifications (@$classlistref) and splits it
# up into alphabetical sub-sections.
sub splitlist {
    my $self = shift (@_);
    my ($classlistref) = @_;
    my $classhash = {};

    # top level
    my $childtype = "HList";
    if (scalar (@$classlistref) <= 39) {$childtype = "VList";}
    my $classifyinfo = $self->get_entry ($self->{'title'}, $childtype, "Invisible");

    # don't need to do any splitting if there are less than 39 (max + min-1) classifications
    if ((scalar @$classlistref) <= 39) {
	foreach $subOID (@$classlistref) {
            if ($subOID =~ /^CLASSIFY\.(.*)$/ 
		&& defined $self->{'classifiers'}->{$1}) 
	    {
                push (@{$classifyinfo->{'contains'}}, 
		      $self->{'classifiers'}->{$1}->{'classifyinfo'});
            } 
	    else 
	    {
		push (@{$classifyinfo->{'contains'}}, {'OID'=>$subOID});
	    }
	}
	return $classifyinfo;
    }
	
    # first split up the list into separate A-Z and 0-9 classifications
    foreach $classification (@$classlistref) {
	my $title = $self->{'reclassifylist'}->{$classification};
	$title =~ s/&(.){2,4};//g; # remove any HTML special chars
	$title =~ s/^(\'|\`|\"|\:|\()//g; # remove any opening punctutation
	$title =~ s/^(.).*$/$1/;
	$title =~ tr/[a-z]/[A-Z]/;

	if ($title =~ /^[0-9]$/) {$title = '0-9';}
	elsif ($title !~ /^[A-Z]$/) {
	    print STDERR "AZCompactList: WARNING $classification has badly formatted title ($title)\n";
	}
	$classhash->{$title} = [] unless defined $classhash->{$title};
	push (@{$classhash->{$title}}, $classification);
    }
    $classhash = $self->compactlist ($classhash);

    my @tmparr = ();
    foreach $subsection (sort keys (%$classhash)) {
	push (@tmparr, $subsection);
    }
    
    # if there's a 0-9 section it will have been sorted to the beginning
    # but we want it at the end
    if ($tmparr[0] eq '0-9') {
	shift @tmparr;
	push (@tmparr, '0-9');
    }

    foreach $subclass (@tmparr) 
    {
	my $tempclassify = $self->get_entry ($subclass, "VList");
	foreach $subsubOID (@{$classhash->{$subclass}}) 
	{
            if ($subsubOID =~ /^CLASSIFY\.(.*)$/ 
		&& defined $self->{'classifiers'}->{$1}) 
	    {
                push (@{$tempclassify->{'contains'}}, 
		      $self->{'classifiers'}->{$1}->{'classifyinfo'});
	    }
	    else
	    {
		push (@{$tempclassify->{'contains'}}, {'OID'=>$subsubOID});
	    }
	}
	push (@{$classifyinfo->{'contains'}}, $tempclassify);
    }

    return $classifyinfo;
}

sub compactlist {
    my $self = shift (@_);
    my ($classhashref) = @_;
    my $compactedhash = {};
    my @currentOIDs = ();
    my $currentfirstletter = "";
    my $currentlastletter = "";
    my $lastkey = "";

    # minimum and maximum documents to be displayed per page.
    # the actual maximum will be max + (min-1).
    # the smallest sub-section is a single letter at present
    # so in this case there may be many times max documents
    # displayed on a page.
    my $min = 10; 
    my $max = 30;

    foreach $subsection (sort keys %$classhashref) {
	if ($subsection eq '0-9') {
	    @{$compactedhash->{$subsection}} = @{$classhashref->{$subsection}};
	    next;
	}
	$currentfirstletter = $subsection if $currentfirstletter eq "";
	if ((scalar (@currentOIDs) < $min) ||
	    ((scalar (@currentOIDs) + scalar (@{$classhashref->{$subsection}})) <= $max)) {
	    push (@currentOIDs, @{$classhashref->{$subsection}});
	    $currentlastletter = $subsection;
	} else {

	    if ($currentfirstletter eq $currentlastletter) {
		@{$compactedhash->{$currentfirstletter}} = @currentOIDs;
		$lastkey = $currentfirstletter;
	    } else {
		@{$compactedhash->{"$currentfirstletter-$currentlastletter"}} = @currentOIDs;
		$lastkey = "$currentfirstletter-$currentlastletter";
	    } 
	    if (scalar (@{$classhashref->{$subsection}}) >= $max) {
		$compactedhash->{$subsection} = $classhashref->{$subsection};
		@currentOIDs = ();
		$currentfirstletter = "";
	    } else {
		@currentOIDs = @{$classhashref->{$subsection}};
		$currentfirstletter = $subsection;
		$currentlastletter = $subsection;
	    }
	}
    }

    # add final OIDs to last sub-classification if there aren't many otherwise
    # add final sub-classification
    if (scalar (@currentOIDs) < $min) {
	my ($newkey) = $lastkey =~ /^(.)/;
	@currentOIDs = (@{$compactedhash->{$lastkey}}, @currentOIDs);
	delete $compactedhash->{$lastkey};
	@{$compactedhash->{"$newkey-$currentlastletter"}} = @currentOIDs;	
    } else {
	if ($currentfirstletter eq $currentlastletter) {
	    @{$compactedhash->{$currentfirstletter}} = @currentOIDs;
	} else {
	    @{$compactedhash->{"$currentfirstletter-$currentlastletter"}} = @currentOIDs;
	} 
    }

    return $compactedhash;
}

1;


