#!/usr/bin/perl

use strict;
use CGI;
use Opals::WebServiceClient qw(wsc_getIllLoanInfo);
use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
);
use Opals::User qw(
    user_currentUser
);
use Opals::ILL qw(
    ill_req_lookup
    ill_req_lookup_union
);
use JSON;
my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $cgi = CGI->new;
# $cgi->param('aaa') returns an array of aaa
my $input = $cgi->Vars();
my $id = $input->{'illId_loanId'};


#my $IllInfoList =getIllInfoList($dbh,$id);
my $IllInfoList =ill_req_lookup($dbh,$id);
if(scalar(@$IllInfoList)==0){
    $IllInfoList=ill_req_lookup_union($dbh,{illId=>$id,loanId=>$id});
}
print "Content-type: text/plain\n\n";
print to_json({illInfoList=>$IllInfoList},{pretty=>1});

#------------------------------------------------------------------------------
sub getIllInfoList{
    my ($dbh,$id) =@_;
    my $sth=$dbh->prepare("select * from opl_ILL_in where (ILL_id=? || ILL_loanId=?)");
    $sth->execute($id,$id);
    my $preIllId=-1;
    my $illInfoList=[];
    my $i=-1;
    my @fieldList = qw(ILL_id title author isbn pubDate pubName pubPlace sf852k sf852h sf852i);
    while(my $rec=$sth->fetchrow_hashref){
       if($preIllId != $rec->{'ILL_id'}){
           $i++;
            $illInfoList->[$i]->{'rid'}=0;
           foreach my $f(@fieldList){
                $illInfoList->[$i]->{$f}=$rec->{$f};
           }
           $illInfoList->[$i]->{'loanList'}=[];           
           $preIllId = $rec->{'ILL_id'};
       }
       push @{$illInfoList->[$i]->{'loanList'}},{loanId=>$rec->{'ILL_loanId'},local_bc=>$rec->{'local_bc'}};
    }
    foreach my $illInfo(@$illInfoList){
        my $bib =getBib($dbh,$illInfo->{'ILL_id'});
        if(defined $bib){
            foreach my $f(keys %$bib){
                $illInfo->{$f}=$bib->{$f};
            }
        }
    }
    return $illInfoList;
}
#------------------------------------------------------------------------------
sub getBib{
    my ($dbh,$illID)=@_;
    my $sth=$dbh->prepare("select m.rid,m.title,m.author,m.isbn,m.pubDate,m.pubPlace,m.pubName
                          from opl_ILL_in l inner join opl_item i on i.barcode=l.local_bc 
                          inner join opl_marcRecord m on i.rid=m.rid
                          where ILL_id=? && local_bc <> '' limit 1");
    $sth->execute($illID);
    my $bib=undef;
    if(my $rec = $sth->fetchrow_hashref){
        $bib=$rec;
    }
    return $bib;


}

