######################################################################
#
#  EPrints OpenURL Internal Resolver
#
######################################################################
#
#  __COPYRIGHT__
#
# Copyright 2000-2008 University of Southampton. All Rights Reserved.
# 
#  __LICENSE__
#
######################################################################

use EPrints;

eval "use URI::OpenURL";
if( $@ )
{
	EPrints::abort( "To enable the OpenURL resolver please install URI::OpenURL: cpan install URI::OpenURL" );
}

use strict;
my $session = new EPrints::Session;
exit( 0 ) unless( defined $session );
# $session->get_database->set_debug( 1 );

my $repository = $session->get_repository();

# Create an OpenURL object
my $uri = URI::OpenURL->new();

# Fill the OpenURL object with the current CGI parameters
my @query;
foreach my $name ($session->param)
{
	for ($session->param( $name ))
	{
		push @query, $name => $_;
	}
}
$uri->query_form( @query );

# warn $uri->dump;

# Get the referent (the referred to object)
my $rft = $uri->referent;

# Get the metadata given for the referent
my %md = $rft->metadata;

# Set up a new search expression
# NB I'm not worrying about filtering because this script will only
# redirect?
my $ds = $session->dataset( "archive" );
my $searchexp = new EPrints::Search(
	keep_cache => 1,
	session => $session,
	dataset => $ds,
	satisfy_all => 1,
);

# Fill in the search expression, mapping OpenURL terms to eprint fields
if( $md{ "aulast" } )
{
	$searchexp->add_field(
		$ds->get_field( "creators_name" ),
		$md{ "aulast" }
	);
}
if( defined($rft->id) )
{
	my $oai_id = EPrints::OpenArchives::archive_id( $session );
	if( defined($rft->id) and $rft->id =~ /^(?:info:ofi\/nam:info:)?oai:$oai_id:(\d+)$/ )
	{
		$searchexp->add_field(
			$ds->get_field( "eprintid" ),
			$1
		);
	}
	else
	{
		$searchexp->add_field(
			$ds->get_field( "official_url" ),
			scalar($rft->id)
		);
	}
}
my %FREE_TEXT = qw(
	title atitle
	publication title
);
while(my( $epf, $ouf ) = each %FREE_TEXT)
{
	next unless defined($md{ $ouf }) and length($md{ $ouf });
	$searchexp->add_field(
		$ds->get_field( $epf ),
		$md{ $ouf },
		"IN"
	);
}
my %EXACT_TERMS = qw(
	volume	volume
	number	number
	series	series
	date	date
	pagerange	pages
);
while(my( $epf, $ouf ) = each %EXACT_TERMS)
{
	next unless defined($md{ $ouf }) and length($md{ $ouf });
	$searchexp->add_field(
		$ds->get_field( $epf ),
		$md{ $ouf }
	);
}

# Urg, either the query was empty or we couldn't use the query given
if( $searchexp->is_blank )
{
	not_found( $session, $uri, "empty_query" );
}

# Perform the search, but we're only interested in the first match
# that comes back (perhaps we should error on more than one match?)
my $list = $searchexp->perform_search();
my( $eprint ) = $list->get_records( 0, 1 );

# No match found for the given query
unless( $eprint ) 
{
	not_found( $session, $uri, "no_match" );
}

my $svc = $uri->serviceType;

my %svc_md = $svc->metadata;

# OAI-PMH
if( $svc->val_fmt and $svc->val_fmt eq 'info:ofi/fmt:kev:mtx:oai_pmh' )
{
	# Location of the OAI-PMH interface
	my $url = $repository->get_conf( "base_url" );
	$url .= "/cgi/oai2";
	$url = URI->new( $url );

	# Get the OAI identifier for this eprint
	my $oai_id = EPrints::OpenArchives::archive_id( $session );
	$oai_id = EPrints::OpenArchives::to_oai_identifier( $oai_id, $eprint->get_id );

	# Add the OAI-PMH arguments
	my %args = %svc_md;
	my $verb = $args{verb} || '';
	if( $verb eq 'GetRecord' || $verb eq 'ListMetadataFormats' )
	{
		$args{identifier} = $oai_id;
	}
	$url->query_form( %args );

	$session->redirect( $url );
}
# Scholarly Service
elsif( $svc_md{ "fulltext" } and
	$svc_md{ "fulltext" } eq 'yes' )
{
	# Redirect to the main document (if possible)
	my @docs = $eprint->get_all_documents();
	if( @docs )
	{
		my $url = $docs[0]->get_url();
		$session->redirect( $url );
	}
}
# Default to redirecting to the abstract page
else
{
	# Redirect to the abstract page
	my $url = $eprint->get_url;
	$session->redirect( $url );
}

$session->terminate;

sub not_found
{
	my( $session, $uri, $message ) = @_;

	$session->not_found( undef ); # Don't print the default 404!

	my %pins = $uri->query_form;
	$_ = $session->make_text($_) for values %pins;

	$session->build_page( 
		$session->html_phrase( "cgi/openurl:${message}_title" ),
		$session->html_phrase( "cgi/openurl:${message}_blurb", %pins ),
		"plain_404" );

        $session->send_page();

	exit(0);
}
