#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Opals::Context;

use Opals::Context;use POSIX qw(
    ceil
);
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_rangedPageList
);

use Opals::Eq_Circulation qw(
 
    circ_getLoanListByRid
    circ_getItemStatus

);

use Opals::Date qw(
    date_text
);

use Opals::Constant;

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

my $cgi = CGI->new;
my $input = $cgi->Vars();

my ($sfOrder, $kw, $boolop);
my @sInput;

 
my $sortAttr    = $input->{'sortAttr'};
my $curPage     = $input->{'pNum'};
my $field       = $input->{'sf0'};
my $kw          = $input->{'kw0'};
my $pSize = 2;
my $curPage = $input->{'pNum'};
($curPage && $curPage >= 1) || ($curPage = 1);
my $offset = ($curPage - 1) * $pSize + $ENV{'Z_INDEX_BASE'};

my $requestXML="";
 $requestXML .="<request>\n";        
 $requestXML .="<page>$curPage</page>\n";
 $requestXML .="<sortAttr>$sortAttr</sortAttr>\n";
 #$requestXML .="<sortOrder>$sortOrder</sortOrder>\n";
 $requestXML .="</request>\n";


my ($resultSize, $resultRecordList) ;
if ($field && $kw){
    ($resultSize, $resultRecordList) =  srch_record_byName($dbh, $field, $kw, $sortAttr, $offset, $pSize);
}

my $retStr;
print "Content-type: text/xml\n\n";

#if ($resultSize > 0){
    $retStr .= toXMLRecord($resultRecordList);
#}

print $retStr;

##########################################################################
sub srch_record_byName{

    my ($dbh, $field, $kw, $sortField, $offset, $pSize) = @_;
    my ($sql, $sqlCount, $sqlItems, $sqlICount);

    ($offset >= 0) || ($offset = 0);
    ($pSize  > 0) || ($pSize  = 1);


    $sql        = "SELECT rid, rname FROM eq_records WHERE MATCH (rname) AGAINST ('$kw' in boolean mode) order by rname ";
    $sqlCount   = "SELECT COUNT(*) FROM eq_records WHERE MATCH (rname) AGAINST ('$kw' in boolean mode) ";
    $sqlItems   = "SELECT iid, barcode FROM eq_items as i INNER JOIN eq_records as r ON i.rid = r.rid 
        WHERE i.rid = ? ORDER BY i.rid, iid ";
    $sqlICount  = "SELECT COUNT(distinct iid) FROM eq_items WHERE rid = ?";
    
    my ($resultSize) = $dbh->selectrow_array($sqlCount, undef);
    my $availRange   = $resultSize - $offset + 1;
   
    if ($availRange > $pSize) {
        $availRange = $pSize;
    }
    elsif ($availRange <=0) {
        $availRange = $resultSize % $pSize;
        $availRange = $pSize if ($availRange == 0); 
        $offset = $resultSize - $availRange + 1;
    }
    my @recordList = ();
    my $sth;
    my $sth_iCount;
    my $sth_items;

    if ($resultSize > 0){              
        my $query = "$sql LIMIT $offset, $availRange";
        $sth = $dbh->prepare($query);
        $sth->execute();                
        while(my ($rid, $rname) = $sth->fetchrow_array()){
            $sth_iCount = $dbh->prepare($sqlICount);
            $sth_iCount->execute($rid);
            my ($iCount) = $sth_iCount->fetchrow_array();
            if ($iCount > 0){
                my @items;
                $sth_items = $dbh->prepare($sqlItems);
                $sth_items->execute($rid);
                my $itemInfo;
                my $status = 'OK';
                while(my ($iid, $barcode) = $sth_items->fetchrow_array()){
                    $itemInfo  = circ_getItemStatus($dbh,{barcode=>$barcode});    
                    if ($itemInfo->{'status'} == IT_STAT_FULL_AVAIL){
                        $status = 'OK';
                    }
                    elsif ($itemInfo->{'status'} == IT_STAT_DAMAGED){
                        $status = 'Damaged';
                    }
                    elsif($itemInfo->{'status'} == IT_STAT_LOST){
                        $status = 'Lost';
                    }
                    elsif($itemInfo->{'status'} == IT_STAT_MISSING){
                        $status = 'Missing';
                    }
                    elsif($itemInfo->{'status'} == IT_STAT_ONLOAN){
                        $status = "On Loan";
                    }
                    push @items, {
                        iid     => $iid,
                        barcode => $barcode,
                        status  => $status,
                        dueDate =>  $itemInfo->{'l_duedate'} ? $itemInfo->{'l_duedate'} : " ",

                    };
                }
                push @recordList, {
                    rid     =>  $rid,
                    rname   =>  $rname,
                    iCount  =>  $iCount,
                    items   =>  \@items,
                };
            }
        }
    }
    $sth->finish;
    $sth_iCount->finish;
    $sth_items->finish;

    return ($resultSize, \@recordList);
}

sub toXMLRecord{
    my ($result) = @_;
    my $text;
    my $recReturned = scalar(@$result);
    my $text = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <equipment recordReturned=\"$recReturned\" >";
        $text .= "<result numberOfHits=\"$resultSize\" recordReturned=\"$recReturned\" />";
        $text .= $requestXML;
    foreach my $rec (@$result){
        $text .= "<record id= \"" . $rec->{'rid'} . "\" > ";
        $text .= "<name >" . $rec->{'rname'} . "</name> ";
        $text .= "<items>";
        foreach my $item(@{$rec->{'items'}}){
            $text .= "<item id =\"" . $item->{'iid'} . "\" >";
            $text .= "<barcode> " . $item->{'barcode'} . " </barcode>";
            $text .= "<status> " . $item->{'status'} . " </status>";
            $text .= "<dueDate>" . $item->{'dueDate'}. "</dueDate>";
            $text .= "</item>";
        }
        $text .= "</items>";
        #my $circInfoXML = getRecCircInfoXML($dbh, $rec->{'rid'});
        #$text .= $circInfoXML;
        $text .= "</record>";
    }
    $text .= "</equipment>";
    return $text;

}

sub getRecCircInfoXML{
    my ($dbh, $rid)= @_;
    my $circInfoXML = "";
    my $loanList = circ_getLoanListByRid($dbh, $rid);
    $circInfoXML = "<circInfo>";
    foreach my $loan (@$loanList){
        $circInfoXML .= "<loan>";
        $circInfoXML .= "<barcode>" .$loan->{'barcode'} . "</barcode>";
        $circInfoXML .= "<due>" .$loan->{'dateDue'} . "</due>";
        $circInfoXML .= "</loan>";
    }
    $circInfoXML .= "</circInfo>";
}
