#!/usr/bin/perl -w -I/opt/eprints2/perl_lib

use EPrints::Session;
use EPrints::EPrint;
use EPrints::Utils;

use LWP::MediaTypes qw( guess_media_type );
use MIME::Lite;
use strict;

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

# Check parameters
my $eprintid = $session->param( "eprintid" );
my $eprint = EPrints::EPrint->new( $session, $eprintid );
if( !defined $eprint )
{
	$session->render_error( $session->html_phrase( 
		"cgi/users/edit_eprint:cant_find_it", 
		id => $session->make_text( $eprintid ) ) );
	$session->terminate();
	exit( 1 );
}

my $email = $session->param( "email" );
if( !defined( $email ) || $email eq "" )
{
	$session->render_error( $session->html_phrase( 
		"request/error:no_email" ) );
	$session->terminate();
	exit( 1 );
}

# Check user is authorised to respond
my $contact_email = undef;
if( $session->get_archive->can_call( "email_for_doc_request" ) )
{
	$contact_email = $session->get_archive->call( "email_for_doc_request", $session, $eprint );
}
if( !defined( $contact_email ) || $session->current_user->get_value( "email" ) ne $contact_email )
{
	$session->render_error( $session->html_phrase( 
		"request/error:not_auth" ) );
	$session->terminate();
	exit( 1 );
}

my $title = $session->html_phrase( "request/respond_page:title" );
my $page = $session->make_doc_fragment();

my $action = $session->param("action");
$action = "reject" if $action ne "accept";

# Has item been made OA in a previous accept?
$action = "oa" if $eprint->get_value( "full_text_status" ) eq "public";

if( $session->get_action_button ne "submit" )
{

	$page->appendChild( $session->html_phrase( "request/respond_page:$action",
		eprint => $eprint->render_citation
	) );

	# Render response form
	my $form =  $session->render_form( "post" );
	$page->appendChild( $form );
	my $textarea = $session->make_element( "textarea", 
		name => "reason",
		"accept-charset" => "utf-8",
		rows => 20,
		cols => 60,
		wrap => "virtual",
	);
	$textarea->appendChild( $session->html_phrase(
		"request/response_email:body_$action",
		eprint => $session->make_text( EPrints::Utils::tree_to_utf8( $eprint->render_citation ) ),
		url => $session->make_text( $eprint->get_url ) ) );
	$form->appendChild( $textarea );

	if( $action eq "accept" )
	{
		my $p = $session->make_element( "p" );
		$form->appendChild( $p );
		my $cb = $session->make_element( "input", type => "checkbox", name => "oa" );
		$cb->appendChild( $session->html_phrase(
			"request/respond_page:fieldname_oa" ) );
		$p->appendChild( $cb );
	}

	$form->appendChild( $session->make_element( "br" ) );
	$form->appendChild( $session->render_hidden_field( "eprintid", $eprintid ) );
	$form->appendChild( $session->render_hidden_field( "email", $email ) );
	$form->appendChild( $session->render_hidden_field( "action", $action ) );
	$form->appendChild( $session->render_action_buttons( submit => $session->phrase( "request/respond_page:action_respond" ) ) );

	$session->build_page( $title, $page );
	$session->send_page();

	$session->terminate();
	exit( 0 );
}

my $subject = $session->phrase( 
	"request/response_email:subject", 
	eprint => $eprint->get_value( "title" ) );

my $mail = $session->make_element( "mail" );
$mail->appendChild( $session->make_text( $session->param( "reason" ) ) );

my $result;
if( $action eq "accept")
{
	# Send acceptance notice with restricted documents attached
	# (remove restrictions if OA flag set)
	my @restricted_docs;
	my $oa = 0;
	$oa = 1 if defined $session->param( "oa" ) && $session->param( "oa" ) eq "on";
	foreach my $doc ( $eprint->get_all_documents )
	{
		if( $doc->is_set( "security" ) && $doc->get_value( "security" ) ne "" )
		{
			push @restricted_docs, $doc;
			if( $oa )
			{
				$doc->set_value( "security", "" );
				$doc->commit;
			}
		}
	}
	if( $oa )
	{
		$eprint->commit;
		$eprint->generate_static;
	}

	$result = send_mail_with_attachments(
		$session->get_archive,
		$session->get_langid,
		"",
		$email,
		$subject,
		$mail,
		$session->html_phrase( "mail_sig" ),
		\@restricted_docs,
	);
}
else
{
	# Send rejection notice
	$result = EPrints::Utils::send_mail(
		$session->get_archive,
		$session->get_langid,
		"",
		$email,
		$subject,
		$mail,
		$session->html_phrase( "mail_sig" ),
	);
}

if( !$result )
{
	$session->render_error( $session->html_phrase( "request/error:email" ) );
	$session->terminate();
	exit( 1 );
}
else
{
	# Render confirmation page
	$page->appendChild( $session->html_phrase( "request/ack_page:$action" ) );
	$session->build_page( $title, $page );
	$session->send_page();
	$session->terminate();
	exit( 1 );
}

sub send_mail_with_attachments 
{
	my ($repository, $langid, $to_name, $to_address, $subject, $body, $sig, $attachments) = @_;

	my $smtphost = $repository->get_conf( 'smtp_server' );
	if( defined $smtphost )
	{
		MIME::Lite->send( 'smtp', $smtphost );
	} else {
		MIME::Lite->send( 'sendmail', $repository->invocation( "sendmail" ) ); 
	}

	# Build email header/body
	my $MAILWIDTH = 80;
	my $repositoryname = EPrints::Session::best_language( $repository, $langid, %{$repository->get_conf( "archivename" )} );
	my $adminemail = $repository->get_conf( "adminemail" );
	my $mime_msg = MIME::Lite->new(
		From => "\"$repositoryname\" <$adminemail>",
		To   => $to_address,
		Subject => "$repositoryname: $subject",
		Type => 'TEXT',
		Data => EPrints::Utils::tree_to_utf8( $body, $MAILWIDTH )->as_string . EPrints::Utils::tree_to_utf8( $sig, $MAILWIDTH )->as_string,
	) or return 0; 

	# Attach each document
	foreach my $doc ( @{$attachments} ) 
	{
		my %files = $doc->files;
		foreach my $file ( keys %files )
		{
			my $path = $doc->local_path . "/" . $file;
			my $type = guess_media_type( $path );
			$mime_msg->attach(
				Type => $type,
				Path => $path,
				Filename => $file,
			) or return 0;
		}
	}

	my $result;
	eval { 	$result = $mime_msg->send; };
	$result ? return 1 : return 0;

}
