#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use Opals::Date qw(
    date_parse
);
use Date::Calc::Object qw(
    :all
);

use Date::Calc qw(
    Delta_Days 
);
use Time::localtime;
my $tm = localtime;
use Opals::Context;#use MARC::File::USMARC;
#use MARC::File::XML;
use Opals::SolrIndex qw(
    slr_search
    srl_buildQuery_datafield
);

use JSON;
my $dbh = Opals::Context->dbh();
my  $barcodeType =Opals::Context->preference('barcodeType');
END { $dbh->disconnect(); }
my $arg=getSearchArg();
my $pSize=(defined $arg && $arg->{'pSize'})? $arg->{'pSize'}:20;
my $pNum =(defined $arg && $arg->{'pNum'})? $arg->{'pNum'}:1;
my $sessionCheck= $arg->{'sessionCheck'};
my $offset=$pSize*($pNum-1);
my $sortAttr=(defined $arg && $arg->{'sortAttr'})? $arg->{'sortAttr'}:'';
my $filter;
my $from =$arg->{'dateImportFrom'};
my $to   =$arg->{'dateImportTo'}; 
if(defined $arg->{'recType'} && $arg->{'recType'} ne ''){
    $filter->{'recType'}=[$arg->{'recType'}];
}
if((defined $from && $from ne '' ) || (defined $to && $to ne '' ) ){
    $filter->{'dateImport'}={from=>$from,to=>$to};
}

my $query=srl_buildQuery_datafield($arg->{'srchFields'},$filter);
open debug, ">/tmp/ss";print debug "$query\n";close debug;

my $rs=slr_search({lQuery=>$query,size=>$pSize,offset=>$offset,recFormat=>'marcJsonObj',sortAttr=>$sortAttr});
my $cgi= CGI->new;

if($rs && $rs->{'hits'}>0 &&  $sessionCheck){
    my @ridArr=();
    foreach my $rec(@{$rs->{'recordList'}}){
        foreach my $f(@{$rec->{'fields'}}){
            if(@$f[0] eq '001'){
                push @ridArr,@$f[1];
                last;
            }
          }
    }

    my $sessionID = $cgi->cookie('globalSessionID');
    my $ridBcList={};
    my $ridList=join(",", @ridArr);
    my $sth=$dbh->prepare("select rid,barcode from opl_sessionVar where ssid ='$sessionID' && var='$sessionCheck' && rid in ($ridList)");
    $sth->execute();
    while(my ($rid,$bc) = $sth->fetchrow_array){
         if(! defined $ridBcList->{$rid}){
             $ridBcList->{$rid}={};
         }
        $ridBcList->{$rid}->{$bc}=1 if(defined $bc);
    }
    foreach my $rec(@{$rs->{'recordList'}}){
        my $rid=undef;
        my $fmtList =$rec->{'format'} ;
        $rec->{'format'}=@$fmtList[0];
        foreach my $f(@{$rec->{'fields'}}){
            if(@$f[0] eq '001' && $ridBcList->{@$f[1]}){
                $rec->{'selected'}=1;
                $rid=@$f[1];
            }
            if(@$f[0] eq '852' ){
                foreach my $sf(@{@$f[3]}){
                    if(@$sf[0] eq 'p' && $ridBcList->{$rid}->{@$sf[1]}){
                        push @$f,'selected';
                        last;
                    }
                }
            }
       }
    }


}
print "Content-type: text/plain\n\n";
print to_json($rs,{pretty=>1});

     
############################################################
sub getSearchArg{
  my $argJson;
  if ($ENV{'REQUEST_METHOD'} eq "POST") {
        my $json ="";
        while (<STDIN>) {
            $json .= $_;
        }
        $argJson = decode_json($json);
   }
   return $argJson;
}

