#!/usr/bin/perl

# PODNAME: koha-coce-url
# ABSTRACT: Generate a JSON structure of Cover url via Coce

use Modern::Perl;
use utf8;
use Pod::Usage;
use Koha::Contrib::Tamil::Koha;
use C4::Context;
use C4::Biblio;
use MARC::Moose::Record;
use YAML;
use LWP;
use LWP::UserAgent;
use JSON;
use Business::ISBN;


binmode(STDOUT, ":encoding(utf8)");



sub usage {
    pod2usage( -verbose => 2 );
    exit;
} 




sub create_json_data {
    my ($query, $coce) = @_;

    #$size = "_SL" . $size . "_";
    my @bibs =
        map { $_->[0] }
        @{C4::Context->dbh->selectall_arrayref($query)};

    my $is_unimarc = C4::Context->preference('marcflavour') eq 'UNIMARC';
    my $tag = {
        isbn  => $is_unimarc ? '010' : '020',
        title => $is_unimarc ? '200' : '245',
    };

    my $koha = Koha::Contrib::Tamil::Koha->new();

    my %record_per_isbn;
    for my $biblionumber (@bibs) {
        my $record = $koha->get_biblio($biblionumber);
        my $field = $record->field($tag->{isbn});
        next unless $field;
        my $isbn = $field->subfield('a');
        next unless $isbn;
        # Clean ISBN
        $isbn = Business::ISBN->new($isbn);
        next unless $isbn;
        next unless $isbn->is_valid;
        $isbn = $isbn->isbn;
        my $title = $record->field($tag->{title});
        next unless $title;
        $title = $is_unimarc
            ? $title->subfield('a')
            : join(' ', map { $_->[1] } @{$title->subf});
        $record_per_isbn{$isbn} = [ $biblionumber, $title ];
    }

    my $url = $coce . "/cover?provider=aws&id=" . join(',', keys %record_per_isbn);
    my $ua = LWP::UserAgent->new(
        agent    => "Koha::Contrib::Tamil/1.0",
        timeout  => 10000,
        ssl_opts => { SSL_verify_mode => 0}
    );
    my $req = HTTP::Request->new(GET => $url);
    my $res = $ua->request($req);
    if ( ! $res->is_success ) {
        say "ERREUR: $url";
        say $res->status_line;
        exit;
    }
    my $content = $res->content;
    my $image_per_isbn = from_json($content);
    my @ret;
    while ( my ($isbn, $image) =  each %$image_per_isbn ) {
        my $infos = $record_per_isbn{$isbn};
        next unless $infos;
        push @$infos, $image;
        push  @ret, $infos;
    }
    say to_json(\@ret, {pretty => 1});
}



usage() unless @ARGV == 2;
create_json_data(@ARGV);

__END__

=pod

=encoding UTF-8

=head1 NAME

koha-coce-url - Generate a JSON structure of Cover url via Coce

=head1 VERSION

version 0.066

=head1 DESCRIPTION

This script generate a JSON array of Cover URLs for biblio records. For example:

 [
  [
    16618,
    "Responsable marketing",
    "https://images-na.ssl-images-amazon.com/images/I/41UUr1J8tqL._SL300_.jpg"
  ],
  [
    16907,
    "Les autruches ne mettent plus la tête dans le sable",
    "https://images-na.ssl-images-amazon.com/images/I/41ZJC0OjcbL._SL300_.jpg"
  ],
  [
    17844,
    "La valeur des idées",
    "https://images-na.ssl-images-amazon.com/images/I/41AVP5yuTnL._SL300_.jpg"
  ]
 ]

The script need three parameters:

=over

=item *

A query returning a list of biblionumber. For example:

  SELECT biblionumber
  FROM biblioitems
  WHERE isbn <> ""
  ORDER BY biblionumber DESC
  LIMIT 100

=item *

Address of a Coce server.

=item *

Size of images

=back

=head1 SYNOPSYS

 koha-coce-url "select biblionumber from biblio limit 100" http:://coce.server

=head1 COPYRIGHT AND LICENSE

Copyright 2018 by Tamil, s.a.r.l.

L<http://www.tamil.fr>

This library is free software; you can redistribute it and/or modify it under
the same terms as Perl 5 itself.

=head1 AUTHOR

Frédéric Demians <f.demians@tamil.fr>

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2021 by Fréderic Démians.

This is free software, licensed under:

  The GNU General Public License, Version 3, June 2007

=cut