
use EPrints;

use strict;

my $session = EPrints::Session->new();

# security?

my $content = "text/xml";
$session->send_http_header( content_type=>$content );
my $family = $session->param( "_name_family" );
my $given = $session->param( "_name_given" );
my $id = $session->param( "_id" );

my $sql = "
SELECT COUNT(eprint.eprintid) AS num_matches,creators_name_honourific,creators_name_given,creators_name_family,creators_name_lineage,creators_id from eprint_creators_name LEFT JOIN eprint_creators_id ON eprint_creators_name.pos = eprint_creators_id.pos AND eprint_creators_name.eprintid = eprint_creators_id.eprintid LEFT JOIN eprint ON eprint_creators_name.eprintid = eprint.eprintid 
WHERE eprint.eprint_status = 'archive' ";
if( EPrints::Utils::is_set( $family ) )
{
	$sql .= "AND creators_name_family LIKE '".EPrints::Database::prep_like_value($family)."\%' ";
}
if( EPrints::Utils::is_set( $given ) )
{
	$sql .= "AND creators_name_given LIKE '".EPrints::Database::prep_like_value($given)."\%' ";
}
if( EPrints::Utils::is_set( $id ) )
{
	$sql .= "AND creators_id LIKE '".EPrints::Database::prep_like_value($id)."\%' ";
}
$sql.="
GROUP BY creators_name_honourific,creators_name_given,creators_name_family,creators_name_lineage,creators_id 
ORDER BY num_matches DESC,creators_name_family,creators_name_given 
LIMIT 40
";

print <<END;
<?xml version="1.0" encoding="UTF-8" ?>

<ul>
END


my $sth = $session->get_database->prepare( $sql );
$session->get_database->execute( $sth , $sql );
my $first = 1;
while( my( $cnt,$h,$g,$f,$l,$id ) = $sth->fetchrow_array )
{
	if( $first )
	{
		print "<li class='ep_first'>";
		$first = 0;
	}
	else
	{
		print "<li>";
	}
	print "$h $g $f $l"; 
	if( defined $id ) { print " ($id)"; }
	print " <small>(author of ".$cnt." item".($cnt>1?"s":"")." in this repository)</small>";
	print "<ul>";
	print "<li id='for:value:relative:_name_family'>$f</li>";
	print "<li id='for:value:relative:_name_given'>$g</li>";
	print "<li id='for:value:relative:_name_honourific'>$h</li>";
	print "<li id='for:value:relative:_name_lineage'>$l</li>";
	print "<li id='for:value:relative:_id'>$id</li>";
	print "</ul></li>\n";
}
print "</ul>";

$session->terminate;

