#!/usr/bin/perl

use EPrints;
use strict;

my $notice;

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

my $from_javascript = $session->param("callback");

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

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


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

my $sneep = EPrints::DataObj::Sneep->new($session, $sneepid, $session->get_repository->get_dataset("sneep"));
if(!defined $sneep){
	print $session->phrase("sneep_does_not_exist");
	exit;
}


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 $session->phrase( 'sneep_no_permission' );
	exit;
}

if( !$content eq "" )
{
	$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' ) );
}

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

        if ( $from_javascript == '1' )
        {
                $session->get_request->content_type( 'application/json' );
                $session->get_request->headers_out->{'Cache-control'} = 'No-cache';
                print "{ 'status': 1, 'sneepid':".$sneep->get_id.", ";
		if($sneep->can_edit){
                        print "'content': '".EPrints::XML::to_string($sneep->render_citation('editable'), undef, 1)."'";
                }else{
                        print "'content': '".EPrints::XML::to_string($sneep->render_citation, undef, 1)."'";
                }
		print ", 'notice': '$notice'" if( defined $notice );
		print " }";
        }
        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"));
        }
}


