#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use JSON;

use Opals::Constant;
use Opals::Context;
use Opals::Session qw(
    SessionHdl_getSSID
);
use Opals::Utility qw(util_getXmlRecord util_restoreLiteral);

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

my $request=getRequest();
my $cgi     = CGI->new;
my $pStatus=1;

my $ssid        = SessionHdl_getSSID($cgi);
my $varName     =$request->{'varName'};
my $pSize       =$request->{'pSize'};
my $pNum        =$request->{'pNum'};
my $briefFormat =0;#$request->{'briefFormat'};
my $status      =$request->{'status'};
my $recFormat   =$request->{'format'};


my ($ridCount,$bcCount,$itemList)=getJobItemList($dbh,$ssid,$varName,$pSize,$pNum,$recFormat);

print "Content-type: text/plain\n\n";

my $rs={status=>1,itemList=>$itemList,bcCount=>$bcCount,ridCount=>$ridCount};
print   to_json($rs);

#-------------------------------------------------------------------------------
sub getJobItemList{
    my ($dbh,$ssid,$vaName,$pSize,$pNum,$format)=@_;
    my $itemList=[];
    my ($ridCount,$bcCount)=(0,0);
    my $sql ="select s.rid,s.barcode ";
    my $sql_count =" select count(distinct rid) as ridCount ,count(barcode) as bcCount ";

    if(!$briefFormat){
        $sql .= " ,title,author,pubPlace,pubName,pubDate,isbn,callNumber ,dateImport,price,location "
    }
    $sql .= "  from opl_sessionVar s ";
    $sql_count .= "  from opl_sessionVar  ";
    if(!$briefFormat){
        $sql .= "  inner join opl_item i on i.barcode=s.barcode inner join opl_marcRecord m on m.rid=i.rid ";
    }
    $sql .= " where ssid= ? && var=? order by sOrder";
    $sql_count .= " where ssid= ? && var=? ";
    

    if(defined $pSize && $pSize && defined $pNum && $pNum){
        my $offset = ($pNum - 1) * $pSize; 
        $sql .= " limit $offset, $pSize";
    }
  # open debug,">/tmp/oo"; print debug "$sql\n$ssid,$vaName"; close debug;
    my $sth_count =$dbh->prepare($sql_count);
    $sth_count->execute($ssid,$vaName);
    if(my $r =$sth_count->fetchrow_hashref){
       ($ridCount,$bcCount)= ($r->{'ridCount'},$r->{'bcCount'});
    }

    my $sth =$dbh->prepare($sql);
    $sth->execute($ssid,$vaName);
    my $ridList={};
    while( my $item=$sth->fetchrow_hashref){
        $item->{'selected'}= TRUE;
        if($format eq 'marcJson' && !defined $ridList->{$item->{'rid'}}){
            my $mJson=getMarcObj(util_getXmlRecord($item->{'rid'}));
            $mJson->{'selected'}= TRUE;
            push @$itemList,$mJson;
            $ridList->{$item->{'rid'}}=1;
        }
        else{
            push @$itemList, $item;
        }

    }
    return ($ridCount,$bcCount,$itemList);

}

#-------------------------------------------------------------------------------
sub getRequest{
  my $fineList=[];
  my $in={};
  if ($ENV{'REQUEST_METHOD'} eq "POST") {
        my $json ="";
        while (<STDIN>) {
            $json .= $_;
        }
        $in = decode_json($json);
   }
   return $in;
}

#////////////////////////////////////////////////////////////////////////////
sub getMarcObj {
    my ($xml) = @_;
    my $marc={};
    my @fields=();

    if($xml =~ s/<leader>(.*?)<\/leader>//){
        $marc->{'leader'}=$1;
    }
    while($xml =~ s/<controlfield tag="(\d{3})">(.*?)<\/controlfield>//){
        push @fields,[$1,$2];
    }
    while($xml =~ s/<datafield tag="(\d{3})" ind1="(\s|\d)" ind2="(\s|\d)">(.*?)<\/datafield>//s){
        my($tag,$ind1,$ind2,$sf)=($1,$2,$3,$4);
        $ind1="#" if($ind1 eq ' ');
        $ind2="#" if($ind2 eq ' ');
        my @f=($tag,$ind1,$ind2);
        my @sfList=();
        while($sf =~s/<subfield code="(.?)">(.*?)<\/subfield>//){
            push @sfList,[$1,util_restoreLiteral($2)] if($1 ne '-');
        }
        push @f,\@sfList;
        push @fields,\@f;
    }
    $marc->{'fields'}=\@fields;
    return $marc;



}


