#!/usr/bin/perl

use EPrints;
use strict;

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

my $sneepid = $session->param("sneepid");
my $sneep = EPrints::DataObj::Sneep->new($session, $sneepid, $session->get_repository->get_dataset("sneep"));

my $content ='';
my $title = '';

if(defined $sneep)
{
	$content = $sneep->get_value("content");
	$title = $sneep->get_value("title");
}
else
{
	$sneepid = ''; #you have requested a sneep which doesnt exist 
}

my $eprintid = $session->param( "eprintid" );
my $eprint = EPrints::DataObj::EPrint->new($session, $eprintid );
	
if(!defined $eprint)
{
        print STDOUT $session->phrase("sneep_not_an_eprint");
        $session->terminate;
        return;
}

#TODO Title phrase
my $page_title = $session->make_text("Sneep Discussion about EPrint ".$eprint->get_id()." - '".$eprint->get_value("title")."'");

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

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

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

my $backtoeprint = $session->make_element( 'a', href=> $eprint->get_url );
$backtoeprint->appendChild( $session->html_phrase( 'sneep_back_to_eprint' ) );

$links->appendChild( $backtoeprint );

if( $type eq "comment" ) 
{
	$links->appendChild( $session->get_repository->call( 'render_sneep', $session, $eprint, 'note' ) );
	$links->appendChild( $session->get_repository->call( 'render_sneep', $session, $eprint, 'tag' ) );			
}
elsif( $type eq "note" )
{
	$links->appendChild( $session->get_repository->call( 'render_sneep', $session, $eprint, 'comment' ) );
	$links->appendChild( $session->get_repository->call( 'render_sneep', $session, $eprint, 'tag' ) );
}
elsif( $type eq "tag" )
{
	$links->appendChild( $session->get_repository->call( 'render_sneep', $session, $eprint, 'comment' ) );
	$links->appendChild( $session->get_repository->call( 'render_sneep', $session, $eprint, 'note' ) );
}

$page->appendChild($links);

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

my %opts;
if($type eq "note")
{
	if( defined $current_user )
	{
		$opts{"userid"} = $current_user->get_id();
	}
	else
	{	
		$page->appendChild($session->html_phrase("sneep_login_to_see_notes"));
		my $complete_page = $session->build_page($page_title, $page);
		$session->send_page($complete_page);
		$session->terminate;
		return;
	}
}

my $sneep_list = $eprint->get_sneeps($type, \%opts);

if(defined $current_user) 
{
        $page->appendChild( $session->get_repository->call( 'render_sneep_input', $session, $eprint, $type , $sneepid, $content, $title)  );
}

if(defined $sneep_list && $sneep_list->count )
{
	$sneep_list->map(sub {
				my ( $session, $dataset, $sneep ) = @_;
				if($sneep->can_edit)
				{
					$page->appendChild($sneep->render_citation("editable_cgi"));
				}
				else
				{
					$page->appendChild($sneep->render_citation);
				}
				
			});
}

my $complete_page = $session->build_page($page_title, $page);
$session->send_page($complete_page);

$session->terminate;
return;

