#!/usr/bin/perl

use EPrints;
use strict;

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

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

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

my $sneep = EPrints::DataObj::Sneep->new($session, $session->param( "sneepid" ) );
binmode(STDOUT,":utf8");

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

my $title = $session->param( 'title' );
my $content = $session->param( 'content' );

#you shouldnt be able to change the type of a sneep right?
#my $type = $session->param("type");

if(!$sneep->can_edit)
{
	print STDOUT $session->phrase( 'sneep_no_permission' );
	$session->terminate;
	return;
}

my $notice;

if( EPrints::Utils::is_set( $content ) )
{
	$sneep->set_value( 'title', $title );
	$sneep->set_value( 'content', $content );
	$sneep->set_value( 'lastmod', EPrints::Time::get_iso_timestamp() );
	$sneep->commit;
}
else
{
	$notice = $session->phrase( 'sneep_no_content_edit', type=>$sneep->get_value( 'type' ) );
}

my $from_javascript = EPrints::Utils::is_set( $session->param("callback") ) ? 1 : 0;

&render_response( $session, $sneep, $from_javascript, $notice );

$session->terminate;

return;

sub render_response
{
	my( $session, $sneep, $from_javascript, $notice ) = @_;

        if ( $from_javascript == '1' )
        {
                $session->get_request->content_type( 'application/json' );
                $session->get_request->headers_out->{'Cache-control'} = 'No-cache';
                print STDOUT '{ "status": 1, "sneepid":"'.$sneep->get_id.'", ';
		if($sneep->can_edit)
		{
			my $string = EPrints::XML::to_string($sneep->render_citation('editable'),undef,1);
			$string =~ s/\r//g;
			$string =~ s/\n//g;
			$string =~ s/\t//g;
			$string =~ s/"/'/g;
			print STDOUT '"content": "'.$string.'" ';
                }
		else
		{
			my $string = EPrints::XML::to_string($sneep->render_citation('editable'),undef,1);
			$string =~ s/\r//g;
			$string =~ s/\n//g;
			$string =~ s/\t//g;
			$string =~ s/"/'/g;
			print STDOUT '"content": "'.$string.'" ';
                }
		print STDOUT ', "notice": "'.$notice.'"' if( EPrints::Utils::is_set( $notice ) );
		print STDOUT ' }';
        }
        else
        {
                my $cgi_url = $session->get_repository()->get_conf("perl_url");
                $session->redirect($cgi_url."/sneep/sneep_page?eprintid=".$sneep->get_value("eprintid")."&type=".$sneep->get_value("type"));
        }
}


