#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use Text::CSV_XS;
use Digest::SHA qw(
    sha1_base64
    sha1_hex
);

use Opals::Context;
use Opals::Template_ajax qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);
use Opals::BarcodeMgmt qw(
    bcm_validateBc
);
use Opals::Date qw(
    date_f005
);
use JSON;
use Opals::BookCover qw(
  bookCover_getUrl
  bookCover_amazon
  bookCover_google
  bookCover_syndetics

);


my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $cgi          = CGI->new;
my $input        = $cgi->Vars();
my $task  = $input->{'task'};
#my $ssidCookie=CGI::Cookie->new(-name=>'globalSessionID',-value=>$ssid);

my $syspref     = tmpl_preference($dbh);
my $validateBc  = $syspref->{'validateBarcode'};
my $barcodeType = $syspref->{'barcodeType'};

my $fname  = $input->{'bcFile'};
my $fdata  = $cgi->param('bcFile');
open debug,">>/tmp/aa";print debug "[$fname][$fdata]\n";close debug;

    my $rs =getBibRecList ();
    getBookCover($rs->{'rs'});
    #print "Set-Cookie: $ssidCookie\n";
    print "Content-type: text/plain\n\n";
    print  encode_json($rs);

   #-------------------------------------------------------------
   sub getBibRecList{
        my $upload_filehandle=$cgi->upload("file")||$fdata;
        my $numBc_added=0;
        my $numlBc_existedInSession=0;
        my @retList=();
        my $maxAllow=200;
        while(<$upload_filehandle>) {
            $_ =~ s/\n|\r//g;
            my $bc=$_;
            my $rid=undef;
            next if($bc eq'');
            my $bibRec  =getBibRec($dbh,$bc);
            if($bibRec){
                $numBc_added++;
                push @retList,$bibRec ;    
            }
            last if($numBc_added>=$maxAllow);
       }
       return {rs=>\@retList,
               numBc_added=>$numBc_added};
    }
   #-------------------------------------------------------------
   sub getBibRec{
       my($dbh,$bc)=@_;
       my $rid=undef;
       $bc     = bcm_validateBc($dbh,$bc,$barcodeType) if($validateBc eq '1');
       my $bibRec=$dbh->selectrow_hashref('select distinct i.callNumber, m.rid,author,title,titleSort,pubDate,pubPlace,pubName,isbn,isbn as isbn_first from opl_marcRecord m  inner join opl_item i using(rid) where i.barcode=?',undef,$bc);
       return $bibRec;
   }
#------------------------------------------------------------------------------
sub getBookCover {
  my ($recList)    = @_;
  my $awsId        = Opals::Context->preference('amazonId');
  my $awsSecretKey = Opals::Context->preference('amazonSecreteKey');
  my $syndeticsId  = Opals::Context->preference('syndeticsId');
  if ($syndeticsId ne '') {
    bookCover_syndetics($recList);
  }
  elsif ($awsId ne '' && $awsSecretKey ne '') {
    bookCover_amazon($recList, $awsId, $awsSecretKey);
  }
  else {
    bookCover_google($recList, "m");
  }

}

