#!/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 MARC::Record;
use MARC::Field;
use MARC::File::XML;
use Opals::Date qw(
  date_f005
);
use Opals::MarcXml qw(
    mxml_update
);
use Opals::Utility qw(
    util_getXmlRecord
);

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 ($permission, $cookieList, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'ajax/ill/saveIllMarcRec.tmpl',
    }
);

my $bcCount= $input->{'holdingCount'};
my $bcLoanIdList=[];
my @dupBcList=();
my $status=1;
my $errCode=0;
my $errMsg="";
for(my $i=0;$i<$bcCount;$i++){
    my ($bc,$loanId)=($input->{"barcode_$i"},$input->{"loanId_$i"});
    if($bc ne ''){
        if(!isDuplicate($dbh,$bc)){        
            push @$bcLoanIdList,{barcode=>$bc,loanId=>$loanId};
        }
        else{
            push @dupBcList,{barcode=>$bc};
        }
    }
}

if(scalar(@dupBcList)>0){
      $status=0;
      $errCode=2;
      $errMsg="Duplicate barcode found";

}
elsif(scalar(@$bcLoanIdList)>0) {
   my $rid= saveRec($dbh);
   if(!$rid){
       $status=0;
       $errCode=1;
       $errMsg="Saving record fail";
   }
}
$template->param(
                 status=>$status,
                 errorCode=>$errCode,
                 errorMsg=>$errMsg,
                 dupBcList=>\@dupBcList
                );
tmpl_write($dbh, $cgi, $cookieList, $template);
#----------------------------------------------------------------------------------------

sub saveRec{
    my ($dbh)=@_;
    my $record;
    my $ill_id=$input->{'ILL_id'}||"";

    my $f008Txt='960618s1973    xxu           000 0 eng d';
    my $f005Txt=date_f005();
    my $title=$input->{'title'}||"";
    my $author=$input->{'author'}||"";
    my $isbn=$input->{'isbn'}||"";
    my $pubPlace=$input->{'pubPlace'}||"";
    my $pubName=$input->{'pubName'}||"";
    my $pubDate=$input->{'pubDate'}||"";
    my $itemType=$input->{'itemType'}||"";
    my $sf852k=$input->{'sf852k'}||"";
    my $sf852h=$input->{'sf852h'}||"";
    my $sf852i=$input->{'sf852i'}||"";
    my $sf852a=$input->{'sf852a'}||"";
    my $sf852b=$input->{'sf852b'}||"";

    
    my $f001 = MARC::Field->new('001', '0');            
    my $f005 = MARC::Field->new('005', $f005Txt);       
    my $f008 = MARC::Field->new('008', $f008Txt );   
    my $f020 = MARC::Field->new('020', '','',a=>$isbn );
    my $f100 = MARC::Field->new('100',1,'',a =>$author);
    my $f245 = MARC::Field->new('245',1,'',a =>$title); 
    my $f260 = MARC::Field->new('260','','',a =>$pubPlace,b=>$pubName,c=>$pubDate); 

    my $rid=getIllMarcRecRid($dbh,$ill_id);
    if(defined $rid && $rid>0){
        my $xml = util_getXmlRecord($rid);
        $record = Opals::Marc::Record::newFromXml($xml);
        foreach my $tag( qw(005 020 100 245 260)){
            my @f=$record->field($tag);
            $record->delete_fields(@f);
        }

    }
    else{
        $record = MARC::Record->new();
        $record->leader('00496nam  2200157 a 4500');
        $record->append_fields($f001);
        $record->append_fields($f008);
    }
    $record->insert_fields_ordered(($f005, $f020, $f100, $f245, $f260));

    my $incomplete   = "true";
    my $temporaryILL = "ILL";

    my $bcList={};
    foreach my $bcLoanId(@$bcLoanIdList){
        my ($bc,$loanId)=($bcLoanId->{'barcode'} , $bcLoanId->{'loanId'});
        $bcList->{$bc} ={status=>'new'};
        my $f852 = MARC::Field->new('852','','',a =>$sf852a,b=>$sf852b,'3'=>$itemType,
                                                k=>$sf852k,h=>$sf852h,i=>$sf852i,
                                                p=>$bc);
        $record->append_fields($f852);

    }


    my $marcXml = MARC::File::XML::record($record);
    foreach my $bcLoanId(@$bcLoanIdList){
        if($bcLoanId->{'loanId'} >0){
            saveIllLocalBc($dbh, $bcLoanId->{'loanId'},$bcLoanId->{'barcode'});
        }
    }
    #open debug,">/tmp/mx"; print debug $marcXml;close debug;
    my $rid = mxml_update($dbh, {rid=>$rid, marcXml=>$marcXml, bcList=>$bcList,tempIll=>$temporaryILL,inComplete=>$incomplete} ) ;

    return $rid;
}


#------------------------------------------------------------------------------
sub isDuplicate{
    my($dbh,$bc)=@_;
    my $sth   =$dbh->prepare("select * from opl_item where barcode=?");
    $sth->execute($bc);
    if(my ($b)=$sth->fetchrow_array){
        return 1;
    }
    return 0;
}

#####################################################
sub getIllMarcRecRid {
    my ($dbh,$ill_id) = @_;
    my $rid=0;
    my $sth=$dbh->prepare("select m.rid from opl_marcRecord m inner join opl_item i using(rid) 
                          inner join opl_ILL_in l on i.barcode=l.local_bc where l.ILL_id=? limit 1");
    $sth->execute($ill_id);
    if(my $r=$sth->fetchrow_hashref){
        $rid=$r->{'rid'};
    }
    $sth->finish;
    return $rid;
}
#####################################################
sub saveIllLocalBc {
    my ($dbh,$loanId,$local_bc) = @_;
    my $sth=$dbh->prepare("update opl_ILL_in set local_bc=? where ILL_loanId=?");
    $sth->execute($local_bc,$loanId);
    $sth->finish;
}

