#!/usr/bin/perl

use strict;
use CGI;
use Time::localtime;

use Opals::Context;
use Opals::Template qw(

    tmpl_read
    tmpl_write
    tmpl_redirect

);
use JSON;
use Opals::Eq_SolrSearch;

use Opals::Equipment qw(

    eq_record_findByRId
    eq_containerItems_getList
);

use Opals::Eq_Circulation qw(

    circ_infoRecord
    circ_getLoanListByRid

);
use Opals::User qw(
    user_currentUserID
);

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

my $cgi = CGI->new;
my $input = $cgi->Vars();
my ($permission, $cookieList, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'eqmnt/recDetailPage.tmpl',
    }
);
my $uIdInfo = user_currentUserID($dbh,$cgi);
my $tm = localtime;
my $curTime = sprintf("%04d%02d%02d%02d%02d%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday, $tm->hour, $tm->min, $tm->sec);

my $kw          = $input->{'kw'};
my $kw1         = $input->{'kw1'};
my $kw2         = $input->{'kw2'};
my $kw3         = $input->{'kw3'};
my $sfield      = $input->{'sfield'};
my $sfield1     = $input->{'sfield1'} || 0;
my $sfield2     = $input->{'sfield2'} || 0;
my $sfield3     = $input->{'sfield3'} || 0;
my $cfield1     = $input->{'cfield1'};
my $cfield2     = $input->{'cfield2'};
my $sortOrder   = $input->{'sortOrder'};
my $sortAttr    = $input->{'sortAttr'};
my $rid         = $input->{'rid'};
my $cat         = $input->{'cat'};
my $curPage     = $input->{'pNum'};
my $pRange      = 5;
my $pSize       = 10;
my $sortAttr    = $input->{'sortAttr'};
my $offset      = $input->{'recRsPos'};
my $searchByCat = $input->{'searchByCat'};
my $searchType  = $input->{'searchType'} || "simple";

my $tmpInput = $input;  
  
    $tmpInput->{'offset'} = $offset;
    $tmpInput->{'pSize'} = 1;

my ($isFirst,$isLast)=(0,0);
my $hits =0;
my ($recId, $recInfo);
my $pNum = $input->{'pNum'};
    ($pNum && $pNum > 0) || ($pNum = 1);
my ($resultSize, $recordList) ;
($curPage && $curPage >= 1) || ($curPage = 1);
my ($numTotal,$numLoan, $numReserve, $numHold, $totalCirc,$totalMissing,$totalDamaged,$totalLost) = (0,0,0,0,0,0,0,0); 
my $itemList = ();
my $displayStyle = (getSearchDisplayStyle($dbh) > 0)?"linear" : "record";
    if (!$rid){
        $template->param(
            error   => 1,);
        my $url = '/bin/eqmnt/searchPage';
        tmpl_redirect($cgi,$url);
    }
    else{
        my $id =0;
        if (($kw && $kw ne "") || ($kw1 && $kw1 ne "") || ($kw2 && $kw2 ne "") || ($kw3 && $kw3 ne "")){
            my $solr_search = Opals::Eq_SolrSearch->new(dbh=>$dbh);
            my $lQuery = $solr_search->eq_slr_buildSearchQuery($tmpInput);
            my $rs = $solr_search->eq_slr_search({lQuery => $lQuery});
            my $hits = $rs->{'hits'};
            my $rec = $rs->{'recordList'}[0];
            $id  = $rec->{'rid'};
            $rid  = ($rec->{'rid'} && $rec->{'rid'}>0)? $rec->{'rid'}:$rid ;
            my $firstIndex=0;
            my $lastIndex= $hits -1;
            $isFirst = ($offset == $firstIndex);
            $isLast  = ($offset == $lastIndex);
        }
        else{ # show newly added record 
            $id = $rid;
            $isFirst = 1;
            $isLast  = 1;
        }
        my ($recId, $recInfo) = eq_record_findByRId($dbh,{recordId=>$rid}); 
        #$rid= $id;
        my $error = 0;
        #if ($recId && $recId == $id){
        if ($recId ){
            ($numTotal,$numLoan,$numReserve,$numHold,$itemList,$totalCirc,$totalMissing,$totalDamaged,$totalLost)=circ_infoRecord($dbh,$rid);
            #foreach my $i (@$itemList) {                         }
        }
        else{
            #check if record is deleted....      
            $error = 1;
            $itemList = [];
        }
    foreach my $i (@$itemList) {
        foreach my $ii (@{$i->{'fields'}}){
            foreach my $k (keys %{$ii}){
                if ($k eq 'sfid' && $ii->{$k} eq '18'){
                    if ($ii->{'sfval'} && $ii->{'sfval'} ne ""){
                        $ii->{'sfval'} = $ii->{'sfval'} . "-" . $ii->{'bldName'};
                    }

                }
            }
        }
    }

    $template->param(
         kw             =>  $kw,
         kw1            =>  $kw1,
         kw2            =>  $kw2,
         kw3            =>  $kw3,
         sfield         =>  $sfield,
         sfield1        =>  $sfield1,
         sfield2        =>  $sfield2,
         sfield3        =>  $sfield3,
         cfield1        =>  $cfield1,
         cfield2        =>  $cfield2,
         sortOrder      =>  $sortOrder,
         sortAttr       =>  $sortAttr,
         pNum           =>  $pNum,
         recordInfo     =>  $recInfo, 
         error          =>  $error,
         rid            =>  $rid,
         recRsPos       =>  $offset,
         numTotal       =>  $numTotal,
         numLoan        =>  $numLoan,
         numReserve     =>  $numReserve,
         numHold        =>  $numHold,
         totalCirc      =>  $totalCirc,
         numReserveTotal=>  $numReserve + $numHold,
         numAvailable   =>  $numTotal - $numLoan - $numHold - $totalMissing - $totalDamaged - $totalLost,
         itemList       =>  $itemList, 
         resultSize     =>  $resultSize,
         isFirst        =>  $isFirst,
         isLast         =>  $isLast,
         cat            =>  $cat,
         searchByCat    =>  $searchByCat,
         searchType     =>  $searchType,
         curTime        =>  $curTime,
         displayStyle    => $displayStyle,
         loggedId        => $uIdInfo->{'uid'} || 0
      );
   }
   my $historyLog = checkHistoryLog($dbh,$rid);
   
   if ($permission && $permission->{'eq_record_edit'}) {
      $template->param(  
        allowEdit       => 1 ,  
        eq_record_edit  => 1,
        historyLog      => $historyLog,
      );
   }

tmpl_write($dbh, $cgi, $cookieList, $template);


sub getShowFieldList {

    #type = "search|brief|full";
    my ($dbh,$type) = @_;
    my $cond="";
    if ($type eq "search"){
        $cond = "showOnSearch";
    }
    elsif ($type eq "brief") {
        $cond = "showOnRecBrief";
    }
    elsif ($type eq "full") {
        $cond = "showOnRecFull";
    }
    else{
        $cond = "showOnSearch";
    }

    my $sth = $dbh->prepare("select id,name, $cond from eq_def where $cond =1");
    my @list;
    $sth->execute();
    while (my $f = $sth->fetchrow_hashref()) {
        push @list, $f;
    }
    return \@list;
}

sub checkHistoryLog {
    my ($dbh,$rid) = @_;
    
    my $sql = "select logId from eq_records where rid = $rid";
    my $logId = $dbh->selectrow_array($sql);
    
    return  (!$logId || $logId eq "")?0:1;

}
sub getSearchDisplayStyle {
    #display record type or linear (for detroit..)
    my ($dbh) = @_;
    my $sth = $dbh->prepare("select count(*) from eq_def where showOnSearch=1 && defType ='item'");
    $sth->execute();
    my $ret = $sth->fetchrow_array();
    $sth->finish;
    
    if (!$ret){
        return 0;
    }
    return $ret;
}

