######################################################################
#
#  Show Last "n" EPrints added.
#
######################################################################
#
#  __COPYRIGHT__
#
# Copyright 2022 University of Southampton.
# EPrints 3.4 is supplied by EPrints Services.
#
# http://www.eprints.org/eprints-3.4/
#
#  __LICENSE__
#
# This file is part of EPrints 3.4 L<http://www.eprints.org/>.
#
# EPrints 3.4 and this file are released under the terms of the
# GNU Lesser General Public License version 3 as published by
# the Free Software Foundation unless otherwise stated.
#
# EPrints 3.4 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with EPrints 3.4.
# If not, see L<http://www.gnu.org/licenses/>.
#
######################################################################

use EPrints;

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

my $ds = $session->dataset( "archive" );

my $citation = $session->config( "latest_tool_citation" );

my $max = 20;
my $mode = $session->param( "mode" );
$mode = "default" if( !defined $mode );
my $search_fields = [];
my $filters = [];
my $conf = $session->config( "latest_tool_modes", $mode );
my $show_conditions = 0;
if( defined $conf )
{
	foreach my $key (keys %{$conf} )
	{
		$citation = $conf->{"citation"} if( $key eq "citation" );
		if( $key eq "filters" )
		{
			$search_fields = $conf->{"filters"};
			$show_conditions = defined $conf->{"show_conditions"} ? $conf->{"show_conditions"} : 1;
		}
		$max = $conf->{"max"} if( $key eq "max" );
	}
}
push @{$filters}, { meta_fields=>[ 'metadata_visibility' ], value=>'show', match=>'EX', describe=>0 };
my $number_to_get = $max;
my $n = $session->param( "n" );
if( $n > 0 && $n <= $max )
{
	$number_to_get = $n;
}
my $indexOffset = $session->param( "indexOffset" );
$indexOffset = 1 if !$indexOffset || $indexOffset =~ /\D/;
my $searchexp = new EPrints::Search(
	allow_blank => 1,
	session => $session,
	search_fields => $search_fields,
	custom_order => "-datestamp",
	dataset => $ds,
	limit => ($indexOffset+$number_to_get-1),
	filters => $filters );
my $title;
if( $show_conditions )
{
	$title = $session->html_phrase( 
		"cgi/latest_tool:title_matching",
		n => $session->make_text( $number_to_get ),
		search => $searchexp->render_conditions_description );
}
else
{
	$title = $session->html_phrase( 
		"cgi/latest_tool:title",
		n => $session->make_text( $number_to_get ) );
}

my $results = $searchexp->perform_search();
$results = EPrints::List->new(
	%$results,
	ids => $results->get_ids( $indexOffset-1, $number_to_get )
);
my $format = $session->param( "output" );
if( defined $format )
{
	my @plugins = $session->plugin_list(
		type=>"Export",
		can_accept=>"list/eprint",
		is_visible=>"all" );
		
	my $ok = 0;
	foreach( @plugins ) { if( $_ eq "Export::$format" ) { $ok = 1; last; } }
	if( $ok ) 
	{
		my $plugin = $session->plugin( "Export::".$format );
		$plugin->initialise_fh( \*STDOUT );
		$session->send_http_header( 
				"content_type" => $plugin->param( 'mimetype' ) );
		# offset links
		my %offsets;
		my $base_url = URI->new( $session->current_url( host => 1 ) );
		$base_url->query_form(
			output => $format,
			n => $number_to_get
		);
		$offsets{first} = "$base_url";
		$offsets{next} = "$base_url&indexOffset=".($indexOffset+$number_to_get);
		if( $indexOffset-$number_to_get >= 1 )
		{
			$offsets{previous} = "$base_url&indexOffset=".($indexOffset-$number_to_get);
		}
		$results->export( $format,
			fh => \*STDOUT,
			link_self => "$base_url",
			totalResults => $results->{dataset}->count( $session ),
			itemsPerPage => $number_to_get,
			startIndex => $indexOffset,
			offsets => \%offsets,
		);
	}
	else
	{
		my $page = $session->html_phrase( 
					"lib/searchexpression:export_error_format" );
		$session->build_page( $title, $page, "latest_tool" );
		$session->send_page();
	}
	
	$results->dispose;
	$session->terminate;
	exit;
}

my @records = $results->get_records( 0, $number_to_get );
$results->dispose;

my $page = $session->make_doc_fragment();
my $type = $session->get_citation_type( $ds, $citation );

my $feeds_conf = $session->config( "latest_tool_feeds" );
if ( defined $feeds_conf )
{
        my $feeds = $session->make_element( "div", class=>"ep_latest_tool_feeds", style=>'padding-top: 6px;' );
        foreach my $feed_type (keys %{$feeds_conf})
        {
                if ( defined $feeds_conf->{$feed_type}->{enabled} && $feeds_conf->{$feed_type}->{enabled} )
                {
                        my $feed = $session->make_element( "span", class=>"ep_search_feed" );
                        my $feed_link = $session->make_element( "a", href=>"/cgi/latest_tool?output=$feed_type" );
                        my $feed_link_icon = $session->make_element( "img", alt=>"[feed]", src=>"/style/images/rss-fill.svg", style=>"border: 0;" );
                        $feed_link->appendChild($feed_link_icon);
                        if ( defined $feeds_conf->{$feed_type}->{label} )
                        {
                                $feed_link->appendText(' ' . $feeds_conf->{$feed_type}->{label});
                        }
                        else
                        {
                                $feed_link->appendText(' ' . $feed_type);
                        }
                        $feed->appendChild($feed_link);
                        $feeds->appendChild($feed);
                }
        }
        $page->appendChild($feeds);
}

my $container;
if( $type eq "table_row" )
{
	$container = $session->make_element( "table", class=>"ep_latest_tool_list" );
}
else
{
	$container = $session->make_element( "div", class=>"ep_latest_tool_list" );
}
$page->appendChild( $container );
my $n = 1;
foreach my $item ( @records )
{
	my $row = $item->render_citation_link( 
		$citation,
		n => [$n++, "INTEGER"] );
	if( $type eq "table_row" || $type eq "div_table_row" )
	{
		$container->appendChild( $row );
	}
	else
	{
		my $div = $session->make_element( "div", class=>"ep_latest_tool_result" );
		$div->appendChild( $row );
		$container->appendChild( $div );
	}
}
my $template = defined $conf->{template} ? $conf->{template} : "default_internal";
$session->build_page( $title, $page, "latest_tool", undef, $template );
$session->send_page();

$session->terminate;
exit;
