#!/usr/bin/perl

use EPrints;
use strict;

# If this gets switched to 1 at any point in the script then an error has occured.
my $error_flag = 0;
my $notice;
my $session = EPrints::Session->new();
exit unless( defined $session );
my $current_user = $session->current_user();

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

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

my $action = $session->param("action");
my $title = $session->param( "title" );
my $content = $session->param( "content" );
my $type = $session->param( "type" );
my $from_javascript = $session->param("callback");
my $sneepid = $session->param("sneepid");

if($action eq "create")
{
	my $eprint = EPrints::DataObj::EPrint->new($session, $eprintid, $session->get_repository->get_dataset("eprint"));
	if(!defined $eprint){
		print $session->phrase("sneep_not_an_eprint");
		exit;
	}
	if( !defined $content || $content eq "" )
	{
		my $message = $session->phrase( 'sneep_content_required', type=>$type );
		create_render_error_response( $from_javascript, $message, $session );
	}

	my $sneep_ds = $session->get_repository()->get_dataset("sneep");

	if($type eq "tag"){
		$content =~ s/\n//;
		my @tags = split(", ", $content); 
		push( @tags, split(",", $content));
		my @sneep_tags;
		foreach my $tag (@tags){
			$tag =~ s/^\s+//;
			$tag =~ s/\s+$//;
			$tag = lc($tag);
			my $data = { type=>$type, title=>$title, content=>$tag, datestamp=>EPrints::Time::get_iso_timestamp(), lastmod=>EPrints::Time::get_iso_timestamp(), userid=>$current_user->get_id(), eprintid=>$eprint->get_id(), eprint_owner=>$eprint->get_user()->get_id() };
			my $new_sneep = EPrints::DataObj::Sneep->create_from_data($session, $data, $sneep_ds);
			$new_sneep->commit;
			push(@sneep_tags, $new_sneep);
		} 
		tags_render_response($from_javascript, $type, \@sneep_tags, $session, $eprint);
		return;
	}	
	my $data = { type=>$type, title=>$title, content=>$content, datestamp=>EPrints::Time::get_iso_timestamp(), lastmod=>EPrints::Time::get_iso_timestamp(), userid=>$current_user->get_id(), eprintid=>$eprint->get_id(), eprint_owner=>$eprint->get_user()->get_id() };

	my $new_sneep = EPrints::DataObj::Sneep->create_from_data($session, $data, $sneep_ds);
	$new_sneep->commit;

	create_render_response($from_javascript, $type, $new_sneep, $session, $eprint);
}
if($action eq "delete"){


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


	#TODO add error phrase
	if(!$sneep->can_edit){
		print "you dont have permission to delete this sneep";
		exit;
	}

	$sneep->remove();
	delete_render_response($from_javascript, $type, $sneep, $session);





}
if($action eq "edit")
{
	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;
	}

	#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 ne "" )
	{
		$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' ) );
	}

	edit_render_response( $from_javascript, $sneep, $session, $notice);

}


sub create_render_response
{
	my( $from_javascript, $type, $sneep, $session, $eprint ) = @_;

	if ( $from_javascript == "1" )
	{
		$session->get_request->content_type("application/json");
		$session->get_request->headers_out->{'Cache-control'} = 'No-cache';
		if($sneep->can_edit){
			print "{ 'status': 1, 'content': '".EPrints::XML::to_string($sneep->render_citation('editable'), undef, 1)."' }";
		}else{
			print "{ 'status': 1, 'content': '".EPrints::XML::to_string($sneep->render_citation, undef, 1)."' }";
		}
	}
	else
	{
		my $cgi_url = $session->get_repository()->get_conf("perl_url");
		$session->redirect($cgi_url."/sneep/sneep_page?eprintid=".$eprint->get_id."&type=".$type);
	}

	$session->terminate;
	exit;
}
sub edit_render_response
{
        my( $from_javascript, $sneep, $session, $notice) = @_;
        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"));
        }
}


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

        if ($from_javascript == "1")
        {
                $session->get_request->content_type("application/json");
                $session->get_request->headers_out->{'Cache-control'} = 'No-cache';
                if($sneep->can_edit){
                        print "{ 'status': 1, 'sneepid': ".$sneep->get_id." }";
                }else{
                        print "{ 'status': 1, 'sneepid': ".$sneep->get_id." }";
                }
        }
        else
        {
                my $cgi_url = $session->get_repository()->get_conf("perl_url");
                $session->redirect($cgi_url."/sneep/sneep_page?eprintid=".$sneep->get_value("eprintid")."&type=".$type);
        }
}

sub tags_render_response{
	
	my( $from_javascript, $type, $tags, $session, $eprint ) = @_;
	#my $frag = $session->make_doc_fragment();
	my $frag = $session->get_repository()->call("render_tags", $session, $eprint );
	
=pod
	foreach my $tag (@{$tags}){
		
		my $span =  $session->make_element("span", id=>"sneep-tag-".$tag->get_id);
		$span->appendChild($session->make_text($tag->get_value("content")));
		my $perl_url = $session->get_repository()->get_conf("perl_url");
		my $delete_link = $session->make_element("a", href=>$perl_url."/users/sneep/sneep?action=delete&sneepid=".$tag->get_id);
		$span->appendChild($delete_link);
		$delete_link->appendChild($session->make_text("Delete"));
		$frag->appendChild($span);
	}
=cut

	if ( $from_javascript == "1" )
	{
		print STDERR "foo\n";
		$session->get_request->content_type("application/json");
		$session->get_request->headers_out->{'Cache-control'} = 'No-cache';
		print "{ 'status': 1, 'content': '".EPrints::XML::to_string($frag, undef, 1)."' }";
	}
	else
	{
		my $cgi_url = $session->get_repository()->get_conf("perl_url");
		$session->redirect($cgi_url."/sneep/sneep_page?eprintid=".$eprint->get_id."&type=".$type);
	}

	$session->terminate;
	exit;
}

sub create_render_error_response
{
	my( $from_javascript, $message, $session ) = @_;

	if( $from_javascript == "1" )
	{
		$session->get_request->content_type( 'application/json' );
		$session->get_request->headers_out->{ 'Cache-control' } = 'No-cache';
		print "{ status: 0, content: '$message' }";
	}

	$session->terminate;
	exit;
}

