#!/usr/bin/perl -w -I/opt/eprints2/perl_lib

use EPrints::Session;

use Citation::Parser::Simple;

use strict;


my $session = new EPrints::Session( 0 );
exit( 1 ) unless( defined $session );

if( $session->param( 'ref' ) )
{
	my( $eprint, $error ) = ref2eprint( $session, $session->param( 'ref' ) );
	if( !defined $eprint )
	{
		$session->build_page( 
			$session->make_text( "Make EPrint from Ref" ),
			$session->make_text( "Error parsing Ref entry: ".$error ) );
		$session->send_page();
	}
	else
	{	
		my $url = '/perl/users/submit?eprintid='.$eprint->get_id.'&_action_edit=1';
		$session->redirect( $url );
	}
}
else
{
	my $page = $session->make_doc_fragment;
	my $p = $session->make_element( "p" );
	$p->appendChild( $session->make_text( "Cut and paste a single reference into the box to create an eprint from it." )) ;
	$page->appendChild( $p );
	my $form = $session->render_form( "post", "refimport" );
	my $textarea = $session->make_element( "textarea", name=>"ref", wrap=>"virtual", rows=>20, cols=>60 );
	$textarea->appendChild( $session->make_text("") );
	$form->appendChild( $textarea );
	$form->appendChild( $session->make_element( "br" ));
	$form->appendChild( $session->make_element( "input", type=>"submit" ));
	$page->appendChild( $form );

	$session->build_page( 
		$session->make_text( "Make EPrint from Ref" ),
	$page );
	$session->send_page();
}
$session->terminate();
exit;

sub ref2eprint
{
	my( $session, $ref ) = @_;

	print STDERR "\n\n\n\n";
	$ref =~ s/\. +([A-Z])\./.$1./g;
	print STDERR "$ref\n";

	my $parser = new Citation::Parser::Simple();
	my $metadata = $parser->parse($ref);
	use Data::Dumper;
	print STDERR Dumper( $metadata );

	my $data = {};
	$data->{userid} = $session->current_user->get_value( "userid" );
	$data->{year} = $metadata->{year};
	$data->{title} = $metadata->{atitle};
	foreach( @{$metadata->{authors}} )
	{
		push @{$data->{authors}}, { main=>$_ };
	}


	print STDERR Dumper( $data );

	
	my $ds = $session->get_archive->get_dataset( "inbox" );
	my $eprint = EPrints::EPrint::create( $session, $ds, $data );

#	if( defined $url )
#	{
#		my $doc = EPrints::Document::create( $session, $eprint );
#		if( $urltype =~ m/^html|pdf|ps|ascii|ppt|msword|other|coverimage$/ )
#		{
#			$doc->set_format( $urltype );
#		}
#		else
#		{
#			$doc->set_format( "other" );
#		}
#		$doc->set_value( "security" , "" );
#		$doc->upload_url( $url );
#		$doc->commit();
#	}

	return $eprint;
}


sub bibclean
{
	my( $text ) = @_;

	return unless defined $text;

	$text =~ s/[{}]//g;
	$text =~ s/\\(.)/$1/g;

	return $text;
}

