package EPrints::Plugin::Export::REF_XML;
# HEFCE Generic Exporter to XML
use EPrints::Plugin::Export::REF;
@ISA = ( "EPrints::Plugin::Export::REF" );
use strict;
sub new
{
	my( $class, %params ) = @_;
	my $self = $class->SUPER::new( %params );
	$self->{name} = "REF2014 - XML";
	$self->{suffix} = ".xml";
	$self->{mimetype} = "text/xml";
	$self->{enable} = EPrints::Utils::require_if_exists( "HTML::Entities" ) ? 1:0;
	return $self;
}
# sf2 / multipleSubmission is not in the XML template so that field is not currently exported (see http://www.ref.ac.uk/media/ref/content/subguide/3.ExampleImportFile.xml)
sub output_list
{
        my( $plugin, %opts ) = @_;
        my $list = $opts{list};
	my $session = $plugin->{session};
	my $institution = $plugin->escape_value( $session->config( 'ref', 'institution' ) || $session->phrase( 'archive_name' ) );
	my $action = $session->config( 'ref', 'action' ) || 'Update';
	# anytime we change to another UoA we need to regenerate a fragment of XML ( etc...)
	my $current_uoa = undef;
	# the tags for opening/closing eg  (ref2) or  (ref1abc)
	my( $main_tag, $secondary_tag ) = $plugin->tags;
	unless( defined $main_tag && defined $secondary_tag )
	{
		$session->log( "REF_XML error - missing tags for report ".$plugin->get_report );
		return;		
	}
print <
	$institution
	
HEADER
	$opts{list}->map( sub {
		my( undef, undef, $dataobj ) = @_;
		my $uoa = $plugin->get_current_uoa( $dataobj );
		return unless( defined $uoa );
		if( !defined $current_uoa || ( "$current_uoa" ne "$uoa" ) )
		{
			my( $hefce_uoa_id, $is_multiple ) = $plugin->parse_uoa( $uoa );
			return unless( defined $hefce_uoa_id );
			if( defined $current_uoa )
			{
				print <
		
CLOSING
			}
			print <
			$hefce_uoa_id
			<$main_tag>
OPENING
			$current_uoa = $uoa;
		}
		my $output = $plugin->output_dataobj( $dataobj );
		return unless( EPrints::Utils::is_set( $output ) );
		print "<$secondary_tag>\n$output\n$secondary_tag>\n";
	} );
	if( defined $current_uoa ) # i.e. have we output any records?
	{
		print <
		
CLOSING
	}
print <