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

use EPrints::Session;
use Data::Dumper;

use strict;




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

my $timeout = 180;
local $SIG{ALRM} = sub { $session->terminate;  die "alarm; bibimport timed out after $timeout seconds.\n" }; # NB: \n required
alarm $timeout;

if( $session->param( 'oaiurl' ) )
{
    my $exec = $session->get_archive->get_conf( "executables", "wget" );
	my $url = $session->param( 'oaiurl' );
	$url =~ s/'/\\'/g;
	open( OAIXML, "$exec '$url' --quiet -O -|" );
	my $xml = join( '', <OAIXML> );
	close OAIXML;

	my $doc = EPrints::XML::parse_xml_string( $xml );
	my @l = $doc->getElementsByTagName( 'metadata' );
	my $md = $l[0];
	my $data = {};
	my $oai_dc = ($md->getElementsByTagNameNS( "http://www.openarchives.org/OAI/2.0/oai_dc/",'dc' ))[0];
	if( defined $oai_dc )
	{
		parse_oai_dc( $oai_dc, $data );
	}

	if( !EPrints::Utils::is_set( $data ) )
	{
		$session->build_page( 
			$session->make_text( "Make EPrint from OAI Record" ),
			$session->make_text( "Error parsing record." ) );
		$session->send_page();
	}
	else
	{
		$data->{userid} = $session->current_user->get_value( 'userid' );
		my $ds = $session->get_archive->get_dataset( "inbox" );
		my $eprint = EPrints::EPrint::create( $session, $ds, $data );
 		my $cache = $eprint->local_path."/oai_source.xml";
		open( C, ">$cache" ); 
		print C $xml;
		close C;
		my $url = '/perl/users/submit?eprintid='.$eprint->get_id.'&_action_edit=1';
		$session->redirect( $url );
	}


	#my $p = $session->make_element( 'pre' );
	#$p->appendChild( $session->make_text( Dumper( $data ) ) );
		#$session->build_page( 
			#$session->make_text( "Make EPrint from OAI" ),
			#$p );
		#$session->send_page();
#
	#if( !defined $eprint )
#	{.
#		$session->build_page( 
#			$session->make_text( "Make EPrint from BibTeX" ),
#			$session->make_text( "Error parsing BibTeX 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 OAI GetRecord URL in" ));
	$page->appendChild( $p );
	my $form = $session->render_form( "post", "oaiimport" );
	my $oaiurl = $session->make_element( "input", size=>60, name=>"oaiurl" );
	$form->appendChild( $oaiurl );
	$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 OAI Record" ),
	$page );
	$session->send_page();
}
$session->terminate();
exit;

sub parse_oai_dc
{
	my( $oaidc, $data ) = @_;

	foreach( $oaidc->getElementsByTagNameNS( 'http://purl.org/dc/elements/1.1/', 'creator' ) )
	{
		my $name = skunge_tag( $_ );
		if( $name =~ m/^\s*([^,]*)\s*,\s*(.*?)\s*$/ )
		{
			push @{$data->{authors}},{ main=>{family=>$1,given=>$2} };
			push @{$data->{creators}},{ main=>{family=>$1,given=>$2} };
		}
	}

	foreach( $oaidc->getElementsByTagNameNS( 'http://purl.org/dc/elements/1.1/', 'title' ) )
	{
		$data->{title} = skunge_tag( $_ );
	}

	foreach( $oaidc->getElementsByTagNameNS( 'http://purl.org/dc/elements/1.1/', 'description' ) )
	{
		$data->{abstract} = skunge_tag( $_ );
	}

	foreach( $oaidc->getElementsByTagNameNS( 'http://purl.org/dc/elements/1.1/', 'identifier' ) )
	{
		my $str =  skunge_tag( $_ );
	
		# if it's probably a URI add it to alt locations
		if( $str =~ m/^[a-z0-9]+:/ )
		{
			push @{$data->{altloc}}, $str;
		}
	}
}

sub skunge_tag
{
	my( $t ) = @_;

	my $x = "";
	foreach my $node ( $t->getChildNodes() )
	{
		$x .= $node->toString();
	}
	return $x;
}
