package EPrints::KlarasConnect::Records;

# EPrints objects -> Source API v1 shapes (RecordSummary, RecordDetail,
# FileRef). Only records in the live archive are ever serialised; fields
# are read through Compat::value so a campus schema missing a field just
# leaves it out.

use strict;
use warnings;

use EPrints::KlarasConnect::Access;
use EPrints::KlarasConnect::Compat;
use EPrints::KlarasConnect::Identity;
use EPrints::KlarasConnect::Settings;

use constant SUBJECT_CACHE_SECONDS => 600;

my %SUBJECTS;    # repoid => { at => t, labels => { id => label } }

# Loads an eprint and returns it only when it is in the live archive.
sub live_eprint
{
	my( $repo, $eprintid ) = @_;
	return undef if !defined $eprintid || $eprintid !~ /\A[1-9][0-9]{0,9}\z/;
	my $ds = EPrints::KlarasConnect::Compat::dataset( $repo, 'eprint' ) or return undef;
	my $eprint = eval { $ds->dataobj( $eprintid ) };
	$eprint = eval { $ds->get_object( $repo, $eprintid ) } if !defined $eprint && !$@;
	return undef if !defined $eprint;
	my $status = eval { $eprint->value( 'eprint_status' ) };
	return defined $status && $status eq 'archive' ? $eprint : undef;
}

sub summary
{
	my( $repo, $eprint, %opts ) = @_;

	my @docs = $opts{docs} ? @{ $opts{docs} } : _documents( $eprint );
	my %access = $opts{access} ? %{ $opts{access} } : _access_for( $repo, \@docs, %opts );

	return {
		id             => '' . $eprint->id,
		title          => _text( EPrints::KlarasConnect::Compat::value( $eprint, 'title' ) ),
		creators       => [ map { $_->{name} } @{ _creators( $eprint ) } ],
		year           => _year( EPrints::KlarasConnect::Compat::value( $eprint, 'date' ) ),
		type           => _type( $repo, $eprint ),
		has_files      => @docs ? \1 : \0,
		has_open_files => ( grep { $access{ $_->id }->{security} eq 'public' } @docs ) ? \1 : \0,
	};
}

sub detail
{
	my( $repo, $eprint, %opts ) = @_;

	my @docs = _documents( $eprint );
	my %access = _access_for( $repo, \@docs, %opts );
	my $out = summary( $repo, $eprint, %opts, docs => \@docs, access => \%access );
	my $base = EPrints::KlarasConnect::Identity::base_url( $repo );

	$out->{abstract}    = _text( EPrints::KlarasConnect::Compat::value( $eprint, 'abstract' ) );
	$out->{creators}    = _creators( $eprint );
	$out->{date}        = _text( EPrints::KlarasConnect::Compat::value( $eprint, 'date' ) );
	$out->{publication} = _text( EPrints::KlarasConnect::Compat::value( $eprint, 'publication' ) );
	$out->{publisher}   = _text( EPrints::KlarasConnect::Compat::value( $eprint, 'publisher' ) );
	$out->{institution} = _text( EPrints::KlarasConnect::Compat::value( $eprint, 'institution' ) );
	$out->{department}  = _text( EPrints::KlarasConnect::Compat::value( $eprint, 'department' ) );
	$out->{keywords}    = _keywords( EPrints::KlarasConnect::Compat::value( $eprint, 'keywords' ) );
	$out->{subjects}    = _subject_list( $repo, EPrints::KlarasConnect::Compat::value( $eprint, 'subjects' ) );
	$out->{divisions}   = _subject_list( $repo, EPrints::KlarasConnect::Compat::value( $eprint, 'divisions' ) );
	$out->{advisors}    = _advisors( $eprint );
	$out->{doi}         = _doi( $eprint );
	$out->{official_url} = _url( EPrints::KlarasConnect::Compat::value( $eprint, 'official_url' ) );
	$out->{landing_url} = _absolute( $base, eval { $eprint->get_url } );
	$out->{citation_text} = _citation( $repo, $eprint );

	$out->{files} = [ map { _file_ref( $repo, $eprint, $_, $access{ $_->id } ) } @docs ];

	return $out;
}

sub file_ref_for
{
	my( $repo, $eprint, $doc, %opts ) = @_;
	my $decision = EPrints::KlarasConnect::Access::for_document( $doc, _access_opts( $repo, %opts ) );
	return _file_ref( $repo, $eprint, $doc, $decision );
}

sub _file_ref
{
	my( $repo, $eprint, $doc, $acc ) = @_;

	my $main = eval { $doc->get_main };
	my $file = defined $main ? eval { $doc->stored_file( $main ) } : undef;
	my $mime = defined $file ? eval { $file->value( 'mime_type' ) } : undef;
	$mime = eval { $doc->value( 'mime_type' ) } if !defined $mime;
	my $format = _format( eval { $doc->value( 'format' ) }, $mime, $main );

	my $label = _text( eval { $doc->value( 'formatdesc' ) } );
	$label = _text( eval { EPrints::Utils::tree_to_utf8( $doc->render_value( 'content' ) ) } ) if !defined $label && eval { $doc->is_set( 'content' ) };
	$label = $main if !defined $label;

	my %ref = (
		id            => '' . $doc->id,
		label         => $label,
		filename      => $main,
		format        => $format,
		mime_type     => $mime,
		size_bytes    => defined $file ? ( eval { $file->value( 'filesize' ) } || 0 ) + 0 : undef,
		security      => $acc->{security},
		embargo_until => $acc->{embargo_until},
		available     => $acc->{available} && defined $file ? \1 : \0,
		reason        => defined $file ? $acc->{reason} : 'not_found',
		# The stored hash, only to those who may fetch the file: from it
		# anyone could confirm a guess of a closed file's contents.
		etag          => defined $file && $acc->{available} ? _etag( $file ) : undef,
		language      => _text( eval { $doc->value( 'language' ) } ),
	);
	return \%ref;
}

sub etag { return _etag( $_[0] ) }

sub _etag
{
	my( $file ) = @_;
	my $hash = eval { $file->value( 'hash' ) };
	return $hash if defined $hash && $hash =~ /\A[0-9a-fA-F]{16,128}\z/;
	my $size = eval { $file->value( 'filesize' ) } || 0;
	my $mtime = eval { $file->value( 'mtime' ) } || '';
	$mtime =~ s/[^0-9]//g;
	return sprintf '%x-%s-%s', $size, $mtime, $file->id;
}

sub _documents
{
	my( $eprint ) = @_;
	my @docs = eval { $eprint->get_all_documents };
	return grep { defined $_ } @docs;
}

sub _access_opts
{
	my( $repo, %opts ) = @_;
	return (
		level           => $opts{level},
		allow_validuser => EPrints::KlarasConnect::Settings::get( $repo, 'allow_validuser' ) ? 1 : 0,
	);
}

sub _access_for
{
	my( $repo, $docs, %opts ) = @_;
	my %o = _access_opts( $repo, %opts );
	return map { $_->id => EPrints::KlarasConnect::Access::for_document( $_, %o ) } @$docs;
}

sub _format
{
	my( $format, $mime, $name ) = @_;
	$mime = '' if !defined $mime;
	$name = '' if !defined $name;
	return 'pdf'  if $mime eq 'application/pdf' || $name =~ /\.pdf\z/i;
	return 'epub' if $mime eq 'application/epub+zip' || $name =~ /\.epub\z/i;
	return 'other';
}

sub _creators
{
	my( $eprint ) = @_;
	my $names = EPrints::KlarasConnect::Compat::value( $eprint, 'creators_name' );
	# ORCID packages add creators_orcid; many campuses put it in creators_id.
	my $ids   = EPrints::KlarasConnect::Compat::value( $eprint, 'creators_orcid' );
	$ids = EPrints::KlarasConnect::Compat::value( $eprint, 'creators_id' ) if ref $ids ne 'ARRAY';
	my @out;
	my $i = 0;
	foreach my $n ( ref $names eq 'ARRAY' ? @$names : () )
	{
		my $name = _person( $n );
		my %c = ( name => $name );
		if( ref $ids eq 'ARRAY' && defined $ids->[$i] && $ids->[$i] =~ m{\A(?:https?://orcid\.org/)?([0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{3}[0-9X])/?\z} )
		{
			$c{orcid} = $1;
		}
		push @out, \%c if length $name;
		$i++;
		last if @out >= 50;
	}
	return \@out;
}

sub _advisors
{
	my( $eprint ) = @_;
	my $names = EPrints::KlarasConnect::Compat::value( $eprint, 'contributors_name' );
	my $types = EPrints::KlarasConnect::Compat::value( $eprint, 'contributors_type' );
	return [] if ref $names ne 'ARRAY';
	my @out;
	for my $i ( 0 .. $#$names )
	{
		my $name = _person( $names->[$i] );
		next if !length $name;
		my $type = ref $types eq 'ARRAY' ? $types->[$i] : undef;
		push @out, { name => $name, role => defined $type ? ( $type =~ m{/([A-Za-z]+)\z} ? lc $1 : _text( $type ) ) : undef };
		last if @out >= 20;
	}
	return \@out;
}

sub _person
{
	my( $n ) = @_;
	return '' if !defined $n;
	return _text( $n ) || '' if !ref $n;
	return '' if ref $n ne 'HASH';
	my @parts = grep { defined $_ && length $_ } map { $n->{$_} } qw( honourific given family lineage );
	my $s = join ' ', @parts;
	$s =~ s/\s+/ /g;
	return $s;
}

sub _type
{
	my( $repo, $eprint ) = @_;
	my $key = EPrints::KlarasConnect::Compat::value( $eprint, 'type' );
	return undef if !defined $key;
	my $label = eval { $repo->phrase( "eprint_typename_$key" ) };
	$label = $key if !defined $label || !length $label || $label =~ /\A\[/;
	return { key => $key, label => _text( $label ) };
}

sub _subject_list
{
	my( $repo, $ids ) = @_;
	return [] if !defined $ids;
	$ids = [ $ids ] if !ref $ids;
	return [] if ref $ids ne 'ARRAY';
	my $labels = _subject_labels( $repo );
	my @out;
	foreach my $id ( @$ids )
	{
		next if !defined $id || !length $id;
		push @out, { id => $id, label => defined $labels->{$id} ? $labels->{$id} : $id };
		last if @out >= 50;
	}
	return \@out;
}

# All subject labels, loaded once per child every few minutes: a record
# page then costs no subject queries at all.
sub _subject_labels
{
	my( $repo ) = @_;
	my $id = $repo->get_id;
	my $c = $SUBJECTS{$id};
	return $c->{labels} if $c && time - $c->{at} < SUBJECT_CACHE_SECONDS;

	my %labels;
	my $ds = EPrints::KlarasConnect::Compat::dataset( $repo, 'subject' );
	if( defined $ds )
	{
		eval {
			$ds->search->map( sub {
				my( undef, undef, $subject ) = @_;
				my $l = eval { EPrints::Utils::tree_to_utf8( $subject->render_description ) };
				$labels{ $subject->id } = _text( $l ) if defined $l;
			} );
			1;
		} or $repo->log( "klaras_connect: could not load subjects: $@" );
	}
	$SUBJECTS{$id} = { at => time, labels => \%labels };
	return \%labels;
}

sub subject_label
{
	my( $repo, $id ) = @_;
	return _subject_labels( $repo )->{$id};
}

sub _keywords
{
	my( $k ) = @_;
	return [] if !defined $k;
	my @k = ref $k eq 'ARRAY' ? @$k : split /\s*[;,\n]\s*/, $k;
	my @out = grep { length } map { _text( $_ ) || '' } @k;
	splice( @out, 30 ) if @out > 30;
	return \@out;
}

sub _doi
{
	my( $eprint ) = @_;
	foreach my $f ( qw( doi id_number ) )
	{
		my $v = EPrints::KlarasConnect::Compat::value( $eprint, $f );
		next if !defined $v || ref $v;
		return $1 if $v =~ m{(10\.[0-9]{4,9}/\S+)}i;
	}
	return undef;
}

sub _citation
{
	my( $repo, $eprint ) = @_;
	my $t = eval { EPrints::Utils::tree_to_utf8( $eprint->render_citation( 'default' ) ) };
	return _text( $t );
}

sub _year
{
	my( $d ) = @_;
	return defined $d && $d =~ /\A([0-9]{4})/ ? $1 + 0 : undef;
}

sub _url
{
	my( $u ) = @_;
	return undef if !defined $u || ref $u;
	return $u =~ m{\Ahttps?://[^\s"<>]+\z}i ? $u : undef;
}

sub _absolute
{
	my( $base, $u ) = @_;
	return undef if !defined $u || ref $u;
	return $u if $u =~ m{\Ahttps?://}i;
	my( $origin ) = $base =~ m{\A(https?://[^/]+)};
	return defined $origin ? $origin . ( $u =~ m{\A/} ? '' : '/' ) . $u : undef;
}

# Plain text: no control characters, trimmed, length-capped.
sub _text
{
	my( $s ) = @_;
	return undef if !defined $s || ref $s;
	$s =~ s/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]//g;
	$s =~ s/\r\n?/\n/g;
	$s =~ s/[ \t]+/ /g;
	$s =~ s/\A\s+|\s+\z//g;
	return undef if !length $s;
	return length( $s ) > 20000 ? substr( $s, 0, 20000 ) : $s;
}

1;
