package Koha::Plugin::Pt::KEEPS::OpacLastDocuments::Core;

use warnings;
use Modern::Perl;

our (@ISA, @EXPORT_OK);
BEGIN {
    require Exporter;
    @ISA = qw(Exporter);

    @EXPORT_OK = qw(
        reloadCache
        getBiblionumbersPrefs
        autoRecords
        biblionumberRecords
    );
}

use lib "/KEEPS/koha/var/lib/koha/plugins";
use Koha::Plugin::Pt::KEEPS::OpacLastDocuments;

my $plugin = Koha::Plugin::Pt::KEEPS::OpacLastDocuments->new;
our $limit = $plugin->retrieve_data("opac_book_news_limit") || 100;
our $numberOfRecords = $plugin->retrieve_data("opac_book_news_records") || 5;
our $selectCriteria = $plugin->retrieve_data("select_criteria") || "biblio";


sub reloadCache {
    my $cacheFile = shift;
    my $records = shift;
    my @lastrecords = ();

    my $count = 0;

	foreach my $record (@{$records}) { 
		if ($count < $numberOfRecords) {	
			my $existentrecord = C4::Biblio::GetMarcBiblio({ biblionumber => $record->{biblionumber} });
			
			if ($existentrecord && !supressed($existentrecord)) {
				my $locatemedia = HasLocalImage($record->{biblionumber});
				my $locatemedia2 = GetLocateMedia ($existentrecord);
				if($record->{imagenumber}){
					$record->{locatemedia} = "/cgi-bin/koha/opac-image.pl?thumbnail=1&imagenumber=".$record->{imagenumber};
					push @lastrecords, $record;
					$count++;
				} elsif ($locatemedia) {
					$record->{locatemedia} = "/cgi-bin/koha/opac-image.pl?thumbnail=1&biblionumber=".$record->{biblionumber};
					push @lastrecords, $record;
					$count++;
				} elsif ($locatemedia2) {
					$record->{locatemedia} = $locatemedia2;
					push @lastrecords, $record;
					$count++;
				} elsif (C4::Context->preference("GoogleJackets")) {
					my $ISBN = $record->{isbn};
					if ($ISBN) {
						my $ua = LWP::UserAgent->new(
							agent => "Mozilla/5.0",
						);
 						my $request = HTTP::Request->new(GET => "http://books.google.com/books?bibkeys=$ISBN&jscmd=viewapi");
						my $response = $ua->request($request);
					
						my $url = thumbnailURL($response->decoded_content);		
						if ($url) {
							$record->{GoogleCover} = $url;
							push @lastrecords, $record;
							$count++;
						}
					}
				}	
			}
		}
	}

	printFile (\@lastrecords, $cacheFile);
}

sub getBiblionumbersPrefs {
	my $dbh = C4::Context->dbh;
	my $sth = $dbh->prepare("
		SELECT plugin_key, plugin_value 
        FROM plugin_data 
        WHERE plugin_class=\"Koha::Plugin::Pt::KEEPS::OpacLastDocuments\" AND plugin_key like \"opac_%%_biblionumbers\"");
	$sth->execute();
	
	my @array;
	while(my $row=$sth->fetchrow_hashref)
	{
		push(@array,$row);	
	}
	$sth->finish;
	return \@array;
}

sub autoRecords {
	my $dbh = C4::Context->dbh;
	my $sth = $dbh->prepare("
		select biblio.biblionumber, title, author, biblioitems.isbn, q.imagenumber as imagenumber from 
		biblio 
			inner join biblioitems on biblio.biblionumber = biblioitems.biblionumber
			inner join biblio_metadata on biblio.biblionumber = biblio_metadata.biblionumber
			left join (select imagenumber, biblionumber from cover_images) as q on biblio.biblionumber = q.biblionumber
		where ExtractValue(metadata,'//datafield[\@tag=\"942\"]/subfield[\@code=\"n\"]') != 1 group by biblionumber order by datecreated DESC, biblionumber DESC limit $limit");
	
	if( $selectCriteria eq 'cover') {
		$sth = $dbh->prepare("
			select biblio.biblionumber, title, author, biblioitems.isbn, MAX(q.imagenumber) as imagenumber from 
			biblio 
				inner join biblioitems on biblio.biblionumber = biblioitems.biblionumber
				inner join biblio_metadata on biblio.biblionumber = biblio_metadata.biblionumber
				inner join (select imagenumber, biblionumber, timestamp from cover_images) as q on biblio.biblionumber = q.biblionumber
			where ExtractValue(metadata,'//datafield[\@tag=\"942\"]/subfield[\@code=\"n\"]') != 1 group by biblionumber order by q.timestamp DESC, biblionumber DESC limit $limit");
	}
	$sth->execute();
	
	my @array;
	while(my $row=$sth->fetchrow_hashref)
	{
		push(@array,$row);	
	}
	$sth->finish;
	return \@array;
}

sub biblionumberRecords {
    my $biblionumbers = shift;
	my $dbh = C4::Context->dbh;
	my @biblionumbers = split( /\s*,\s*/, $biblionumbers );
	my $biblionumbers_param = join( "','", @biblionumbers );

	my $query_string = "SELECT biblio.biblionumber, biblio.title, biblio.author, biblioitems.isbn, cover_images.imagenumber as imagenumber FROM biblio INNER JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber inner join cover_images on biblio.biblionumber = cover_images.biblionumber WHERE biblio.biblionumber IN ('". $biblionumbers_param ."') group by biblionumber";

	if( $selectCriteria eq 'cover') {
		$query_string = "SELECT biblio.biblionumber, biblio.title, biblio.author, biblioitems.isbn, MAX(cover_images.imagenumber) as imagenumber FROM biblio INNER JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber inner join cover_images on biblio.biblionumber = cover_images.biblionumber WHERE biblio.biblionumber IN ('". $biblionumbers_param ."') group by biblionumber";
	}

	my $sth = $dbh->prepare($query_string);
	$sth->execute();

	my @array;
	while(my $row=$sth->fetchrow_hashref)
	{
		push(@array,$row);	
	}
	$sth->finish;
	return \@array;
}

sub HasLocalImage {
	my $biblionumber = shift;
	my $haslocalimage = 0;

	my $dbh = C4::Context->dbh;
	my $sth = $dbh->prepare("select imagenumber, biblionumber, mimetype from cover_images where biblionumber = $biblionumber");
	$sth->execute();
	
	while(my $row=$sth->fetchrow_hashref)
	{
		$haslocalimage = 1;
	}
	$sth->finish;
	return $haslocalimage;
}

sub supressed {
	my $record = shift;
	my $supressed = undef;

	foreach my $field ($record->fields()) {
		if ($field->tag() == 942) {
			my @subfields = $field->subfield('n');
			foreach my $subfield (@subfields) {
				if ($subfield eq "1") {
					$supressed = "true";
				}
			}
		}
	}

	return $supressed;
}


sub GetLocateMedia {
	my $record = shift;
	my $locatemedia = undef;

	foreach my $field ($record->fields()) {
		if ($field->tag() == 856) {
			my @subfields = $field->subfield('u');
			foreach my $subfield (@subfields) {
				if ((index $subfield,"locatemedia.aspx") != -1) {
					if ($field->subfield('2') && $field->subfield('2') =~ "Capa") {
						my $filename = filename($subfield);						
						if (-e $filename) {
							$locatemedia = $subfield;
						}
					}
				} 
			}		
		}	
	}

	return $locatemedia;
}

sub thumbnailURL {
	my $response = shift;
	my $url = "";
	if ($response =~ m/(\"thumbnail_url\":\")(.*)/) {
		$url = substr $2,0,index ($2,'"');#CGI::escapeHTML(substr $2,0,index ($2,'"'));
		$url =~ s/\\u0026/&/g;
		$url =~ s/zoom=5/zoom=1/;
		$url = CGI::escapeHTML($url);
	}
	return $url;
}

sub filename {
	my $path = shift;
	my $filename = undef;

	# my $dir = context_intranetdir();
	my $dir = C4::Context->config('intranetdir');

	$filename = substr $path,(index $path,"capa=")+5;
	$filename = $dir."/../../img/".$filename;
	
	return $filename;
}

sub printFile {
	my $records = shift;
    my $file = shift;

	open my $outputFile,">:utf8",$file;

	foreach my $record (@{$records}) {
		if ($record->{locatemedia}) {
			print $outputFile $record->{biblionumber}."##".$record->{locatemedia}."##".sanitize($record->{title})."##".sanitize($record->{author})."\n";
		} elsif ($record->{GoogleCover}) {
			print $outputFile $record->{biblionumber}."##".$record->{GoogleCover}."##".sanitize($record->{title})."##".sanitize($record->{author})."\n";		
		}
	}

	close $outputFile;
}

sub sanitize {
	my $string = shift;
	$string =~ s/\R//g;
	return $string;
}

sub readFile {
    my $cacheFile = shift;
	my @records = ();
	
	open(MYINPUTFILE, "<:utf8",$cacheFile);

	while(<MYINPUTFILE>) {
		my($line) = $_;
		chomp $line;

		if ($line ne "") {
			my @fields = split("##", $line);
			my %record = ();
			$record{biblionumber} = $fields[0];
			if ($fields[1] && ($fields[1] =~ "locatemedia" || index($fields[1], "opac-image.pl") != -1)) {
				$record{locatemedia} = $fields[1];
			} else {
				$record{GoogleCover} = $fields[1];
			}
			$record{title} = $fields[2];
			$record{author} = $fields[3] if $fields[3];
			push @records,\%record;
		}
	}

	close MYINPUTFILE;

	return \@records;
}	

1;