# warns of duplicates based on a simple title string match

use EPrints;

use strict;
use warnings;

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

# security?

# How many chars needed before we try and suggest duplicates?
my $need = 5;

my $q = $session->param( "q" ) || "";

exit unless length( $q ) >= $need; 

my $eprintid = $session->param( "eprintid" );
if( !defined($eprintid) )
{
	$session->get_repository->log( "title_duplicates lookup script called without eprintid argument: ".join(',',$session->param));
	exit(0);
}
elsif( $eprintid =~ /^([0-9]+)$/ )
{
	$eprintid = $1;
}
else
{
	EPrints::abort "Requires numeric eprintid argument";
}

my $database = $session->get_database;
my $dataset = $session->get_repository->get_dataset( "eprint" );

my $Q_table = $database->quote_identifier($dataset->get_sql_table_name);
my $Q_eprintid = $database->quote_identifier( "eprintid" );
my $Q_eprint_status = $database->quote_identifier( "eprint_status" );
my $Q_title = $database->quote_identifier( "title" );

my $sql = "SELECT $Q_eprintid" .
	" FROM $Q_table" .
	" WHERE " .
	" $Q_eprint_status=" .  $database->quote_value( "archive" ) .
	" AND $Q_eprintid!=$eprintid" .
	" AND $Q_title IS NOT NULL" .
	" AND $Q_title LIKE " .
	$database->quote_value( EPrints::Database::prep_like_value( $q ) . '%' ) .
	" LIMIT 10";

my $doc = $session->make_doc_fragment();

my $sth = $session->get_database->prepare( $sql );
$session->get_database->execute( $sth , $sql );

my $base_url = $session->get_repository->get_conf( "base_url" );

my $warning =<<END;
The following records matching this title already exist in the archive.
Please check that you are not entering a duplicate record.
END

my $row = $sth->fetch;

exit unless defined $row;

$doc->appendChild( my $div = $session->render_message( "warning", $session->make_text( $warning) ) );

$div->appendChild( my $ul = $session->make_element( 'ul' ));

my $count = 0;
my $first = 1;

do
{
	my( $eprintid, $title ) = @$row;
	$ul->appendChild( my $li = $session->make_element( 'li' ) );
	if( $first )
	{
		$li->setAttribute( 'class', 'ep_first' );
		$first = 0;
	}
	if( ++$count > 5 )
	{
		$li->appendChild( $session->make_element( 'a',
					target => '_blank',
					href => "$base_url/$eprintid",
					) )->appendChild( $session->make_text( "\"$title\"" ) );
	}
	else
	{
		my $eprint = EPrints::DataObj::EPrint->new( $session, $eprintid );
		$li->appendChild( $eprint->render_citation_link( "default", target=>"_blank" ) );
	}
} while( $row = $sth->fetch );

$session->send_http_header( content_type => "text/xml; charset=UTF-8" );

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

END
	EPrints::XML::to_string( $doc, "utf-8", 1 );

EPrints::XML::dispose( $doc );

$session->terminate;
