#!/usr/bin/perl

use EPrints;
use strict;

my $session = new EPrints::Session;
return unless( defined $session );

binmode( STDOUT, ":utf8" );

my $eprintid = $session->param("eprintid");

my $eprint = EPrints::DataObj::EPrint->new( $session, $session->param( "eprintid" ) );

if(!defined $eprint)
{
	print STDOUT $session->phrase("sneep_not_an_eprint");
	$session->terminate;
	return;
}

my $type = $session->param("type");

if(!defined $type)
{
	print STDOUT $session->phrase("sneep_no_type");
	$session->terminate;
	return;
}

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

my $current_user = $session->current_user();

# Only do this if a user is logged in.
if (defined $current_user) 
{
	$doc_frag->appendChild( $session->get_repository->call( 'render_sneep_input', $session, $eprint, $type ) );
}

my $sneep_list = $eprint->get_sneeps($type);

my $sneep_list_div = $session->make_element("div", class=>"ep_sneep_".$type."_list");

#if( $type eq "note" && !defined $current_user )
if( !defined $current_user )
{
	my $login_link = $session->make_element( "a", href => "/cgi/users/login?target=".$session->get_repository->get_conf("base_url")."/$eprintid/" );
	$login_link->appendChild( $session->html_phrase( "sneep_login"  ) );
	$sneep_list_div->appendChild( $session->html_phrase( "sneep_no_user_$type", login => $login_link ) );
#type=>$session->make_text( $type ) ) );
}
#else
#{
	if( $sneep_list->count )
	{
		$sneep_list->map( sub {
			my ( $session, $dataset, $sneep ) = @_;
			#only view your own notes
			if( $sneep->get_value("type") eq "note" )
			{ 
				return if( !defined $current_user || $sneep->get_value( "userid" ) != $session->current_user->get_id );
			}
			if( $sneep->can_edit )
			{	
				$sneep_list_div->appendChild( $sneep->render_citation("editable") );
			}
			else
			{
				$sneep_list_div->appendChild( $sneep->render_citation );
			}
		});
	}
	else
	{
		my $no_sneeps_message = $session->make_element( "p", id=>"ep_sneep_no_".$type."s" );
		$no_sneeps_message->appendChild( $session->html_phrase( "sneep_no_sneeps", 
			type=>$session->make_text( $type ),
			title=>$session->make_text( $eprint->get_value( 'title' ) ) ) 
		);
		$sneep_list_div->appendChild( $no_sneeps_message );
	}
#}

$doc_frag->appendChild($sneep_list_div);

$session->get_request->headers_out->{'Cache-Control'} = 'No-Cache';
print STDOUT EPrints::XML::to_string( $doc_frag, undef, 1 );

$session->terminate;
return;


