package Opals::RecordInfoHTML;
require Exporter;
@ISA       = qw(Exporter);

@EXPORT_OK = qw(
    rinfo_getBibRecordHTML
    rinfo_getSimilarItemsHTML
    rinfo_getRecCircInfoHTML
    rinfo_getPageNavForm_search
    rinfo_getRatingInfoHTML

    pf_getPfHTML
    marc21_getMarcRec
    getReserveShelfHTML
);
# Version number
$VERSION   = 0.01;
use strict;

use POSIX qw(
    ceil
    floor
);
use Opals::Constant;
use HTML::Template;
use Opals::MarcXmlParser; 
use Opals::Circulation qw(
    circ_getItemStatus
    circ_infoRecord
    circ_getRecCircStatus
    eCirc_isReserveTo
    eCirc_isOnLoanTo
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);
use Opals::Date qw(
    date_now
    date_text
    date_today
    date_parse
);
use Opals::BookCover qw(
    bookCover_getUrl
    bookCover_amazon
    bookCover_google
    bookCover_syndetics

);
use Opals::Utility qw(
util_restoreLiteral
);
use Opals::Rating qw(
    cmntRating_getInfoByRid
);
use Opals::SolrIndex qw(
    slr_getSimilarItem
      
);
use Opals::User qw(
    user_currentUser
);

use Opals::Marc21 qw(
    mc21_parseRecord
);

use Opals::Pathfinder qw(
    pf_getRecById
    pf_parsePfXml
);
use Opals::Ebook qw(
    eb_getLicense
);

use Opals::ReserveShelf qw(
    rs_getReserveShelfByID
    rs_getRShelfFromRecordId
);
use JSON;

use Opals::Constant;

sub _getTemplate{
    my($path,$fname)=@_;
    my $rootDir   = Opals::Context->config('rootDir');
    my $template = HTML::Template->new(    
                filename            => $fname ,
                path                => "$rootDir/$path",
                global_vars         => 1,
                die_on_bad_params   => 0,
                cache               => 1,
                shared_cache        => 0,
                loop_context_vars   => 1,);
    $template->param(http_host=>$ENV{'HTTP_HOST'});
    return $template;    
}
#=======================================================
sub rinfo_getBibRecordHTML{
    my($dbh,$rec,$srchPage)=@_;
    my $rootDir   = Opals::Context->config('rootDir');
    my  $showARL         =Opals::Context->preference('showARL');
    my $template = _getTemplate("/htdocs/theme/opals/search/","recInfo.inc");
    getBookCover($rec,'mc',1);
    my $reservationSysType=Opals::Context->preference("reservationSysType");
    foreach my $f(keys %$rec){
        $template->param($f =>$rec->{$f});
    }
    my $infoMsgMap    =loc_getMsgFile('record/bib_info.msg');
    my $formatMsgMap  =loc_getMsgFile('search/facet.msg',{});
    my $ebMsgMap      =loc_getMsgFile('ebook.msg');
    loc_write($template,$ebMsgMap);

    my $fmtList =$rec->{'format'} ;
    foreach my $i (@$fmtList){
        $i->{'itemTxt'}=$formatMsgMap->{$i->{'item'}};
    }
    loc_write($template,$infoMsgMap);
    
    if(Opals::Context->preference('syndeticsId') eq '' &&
       Opals::Context->preference('googlePreview') eq '1' &&
       $rec->{'isbn_first'} ne ''){
        $template->param(showGooglePreview=>1);

    }
   if(defined $srchPage && $srchPage ne ""){
        my $pageReq = $srchPage."Page";
        $template->param("ebookPage"          =>1,pageReq             =>$pageReq);
   }

    $template->param(showARL        =>$showARL,
                     bid            =>$rec->{'bid'},
                     isOPALSEbook   =>$rec->{'isOPALSEbook'},                     
                     isEbook   =>$rec->{'isEbook'},
                     reservationSysType =>$reservationSysType
                     ); 

    
    return $template->output;
}
#=======================================================
sub rinfo_getRecCircInfoHTML{
    my($dbh,$rec,$op)=@_;
    my $rid     =$rec->{'rid'};
    my $itemList=$rec->{'itemList'};
    my $fmtList =$rec->{'format'} ;

my $scriptRegistry =SCRIPT_REGISTRY;
    my $template = _getTemplate("/htdocs/theme/opals/search/","recCircDetail.inc");
    my $rootDir   = Opals::Context->config('rootDir');
    my ($numTotal, $numLoan, $numReserve, $numHold,$numAvailable, $items,$totalCirc,$bid) =(0,0,0,0,0,undef,0,0);
    ($numTotal, $numLoan, $numReserve, $numHold, $items,$totalCirc,$bid)
            = circ_infoRecord($dbh,$rid,$itemList);
     $numAvailable = $numTotal - $numLoan - $numHold;
    my $i=0;
    foreach my $r (@$itemList){
        $r->{'odd'} = ($i % 2 == 1)? 1:0;
        $i +=1;
    }

    getItemStatus($dbh,$itemList);
    #START:  Wed, May 09, 2012 @ 09:58:48 EDT
    my $pf = getPathfinder($dbh,$rec->{'rid'});
    #END: Wed, May 09, 2012 @ 09:59:11 EDT
    my $reserveShelf = rs_getRShelfFromRecordId($dbh,$rec->{'rid'});
    my $genreList=getRelGenreList($dbh,$rec->{'rid'});
    my $curUserId =0;
    my $cgi = CGI->new;
    my($returnable,$loanable,$reserveable,$readable,$addable)=(0,0,0,0,0);
    
    if(defined  $rec->{'bid'} && $rec->{'bid'} >0){
        $addable =1;
        my $ebLicense = eb_getLicense($dbh,$rec->{'bid'});
        if($ebLicense->{'licenseType'} eq 'free'){
            $readable=1;
        }
        else{
            my ($errCode, $ck, $user) = user_currentUser($dbh, $cgi);
            $curUserId = $user->{'uid'} if($user);
            $readable=eCirc_isOnLoanTo($dbh,$curUserId,$rec->{'bid'});
            if($readable){
                $returnable =1;
            }
            elsif($rec->{'available'}>0){
                $loanable = 1;
            }
            elsif(!eCirc_isReserveTo($dbh,$curUserId,$rec->{'bid'})){
                $reserveable =1;  
            }
       }

    }
 foreach my $sriptName(keys %$scriptRegistry){
        $template->param($sriptName=>$scriptRegistry->{$sriptName}->{'url'});

  } 
    $template->param(itemList      => $itemList) if(ref($itemList) eq 'ARRAY');
    $template->param(
                    rid            => $rid,
                    bid            => $rec->{'bid'},
                    totalHolding   => $numTotal,
                    onLoan         => $numLoan,
                    totalCirc      => $totalCirc,
                    onReserve      => $numReserve,
                    onHold         => $numHold,
                    available      => $numAvailable,
                    formatList     => $fmtList,
                    pf             => $pf,
                    reserveShelf   => $reserveShelf,
                    genreList   => $genreList,
                    isOPALSEbook   => $rec->{'isOPALSEbook'},
                    isEbook        =>$rec->{'isEbook'},
                    curUserId      => $curUserId,
                    readable       => $readable,
                    returnable     => $returnable,
                    loanable       => $loanable,
                    reserveable    => $reserveable,
                    addable        => $addable
                    );
    $template->param( uriList   =>$rec->{'uriList'}) if($rec->{'uriList'});
    my $infoMsgMap              =loc_getMsgFile('/record/circ_info.msg');
    loc_write($template,$infoMsgMap);
    my $ebMsgMap  =loc_getMsgFile('ebook.msg',$infoMsgMap);
    loc_write($template,$ebMsgMap);
    if(defined $op){
        foreach my $o(keys %{$op}){
            $template->param($o=> $op->{$o});
        }
    }
    return $template->output;
}
#======================================================================================
#Thu, May 10, 2012 @ 08:43:42 EDT
#
sub getPathfinder{
    my ($dbh,$rid) = @_;
    my $pfList =[];
my  $sth = $dbh->prepare(<<_STH_);
   select distinct pfId ,title pfTitle from pf_ridMap m inner join pf_record r using (pfId) where rid=?
_STH_

    $sth->execute($rid); 
    while (my $pf =$sth->fetchrow_hashref){
        push @$pfList,$pf;
    }
    $sth->finish;
    return $pfList;
}

#=======================================================
#Tue, Sep 07, 2010 @ 15:22:57 EDT
sub getItemStatus{
    my($dbh,$itemList)=@_;
    foreach my $item(@$itemList){
        my $s=circ_getItemStatus($dbh,$item->{'barcode'});
        my $od = 0;
        $item->{'status'} =$s->{'status'};
        if($item->{'status'}==IT_STAT_MISSING || $item->{'status'}== IT_STAT_CLAIM_RETURN || $item->{'status'}== IT_STAT_CLAIM_NEVER_LOAN){ 
            $item->{'missing'}=1;
        }
        elsif($item->{'status'}==IT_STAT_DAMAGED){
            $item->{'damaged'}=1;
        }
        elsif($item->{'status'}==IT_STAT_LOST){
            $item->{'lost'}=1;
        }
        elsif($item->{'status'}==IT_STAT_ON_ORDER){
            $item->{'onOrder'}=1;
        }
        elsif($item->{'status'}==IT_STAT_IN_PROCESSING){
            $item->{'inProcessing'}=1;
        }
        elsif($item->{'status'}==IT_STAT_IN_REPAIR){
            $item->{'inRepair'}=1;
        }
        elsif($item->{'status'}==IT_STAT_WEED){
            $item->{'weed'}=1;
        }
        elsif($item->{'status'}==IT_STAT_ONLOAN){
            my $today = date_today();
            my $dd = date_parse($s->{'l_duedate'});
            $item->{'overdue'} = ($dd  && $dd <$today) ? 1 : 0;
            $item->{'duedate'}=date_text($s->{'l_duedate'});
        }


    }

   
}


#=======================================================
sub rinfo_getPageNavForm_search{
    my ($cgi)=@_;
    my $input=$cgi->Vars();
    my @recType     = $cgi->param('recType');
    my @location    = $cgi->param('location');
     my $navFormInput=[];
    foreach my $iName(keys %$input){
        next if($iName eq 'op' && $input->{$iName} eq 'delRec');
        push @$navFormInput,{name=>$iName, value=>$input->{$iName}} if($iName ne'recType' && $iName ne 'location');
    }
    foreach my $rType(@recType){
        push @$navFormInput,{name=>'recType', value=>$rType};
    }
    foreach my $loc(@location){

        push @$navFormInput,{name=>'location', value=>$loc};
    }
     my @fieldArr =qw(languageFilter formatFilter authorFilter subjectFilter deweyFilter eraFilter genreFilter callnumberPrefixFilter);
    foreach my $f(@fieldArr){
        if(!defined $input->{$f}){
            push @$navFormInput,{name=>$f, value=>''};
        }
    }
    if(!defined $input->{'pNum'}){
        push @$navFormInput,{name=>'pNum', value=>1 };
    }
    
    if($ENV{'SCRIPT_NAME'} =~ m/recDetailPage/){
        my $refUrl=$input->{'back2RsPageURL'};
        if(!defined $input->{'back2RsPageURL'} && $ENV{'HTTP_REFERER'} !~ m/zimport/){
            $refUrl=$ENV{'HTTP_REFERER'};
            push @$navFormInput,{name=>'back2RsPageURL', value=>$refUrl };
        }
    }
    my $rootDir   = Opals::Context->config('rootDir');
   # my $template = _getTemplate("/htdocs/theme/opals/search/","rsPageNavForm.inc");
    my $template = HTML::Template->new(    
            filename            => "rsPageNavForm.inc",
            path                => "$rootDir/htdocs/theme/opals/search/",
            die_on_bad_params   => 0,
            cache               => 1,
            shared_cache        => 0,
            loop_context_vars   => 1,);
    $template->param(navFormInput=>$navFormInput) ;
      
    return $template->output;
}


#=======================================================
sub rinfo_getSimilarItemsHTML{
    my($rec)=@_;
    my $rid= $rec->{'rid'};  
    my $litForm=$rec->{'literaryForm'};
    my $fiction=($litForm =~ m/^fiction$|^shortStories$/)?1:0;
    my $similarRecList = slr_getSimilarItem($rid,$fiction);
    foreach my $rec(@$similarRecList){
        getBookCover($rec,'mc',1);
    }
    my $rootDir   = Opals::Context->config('rootDir');
    my $template = _getTemplate("/htdocs/theme/opals/search/","similarItems.inc");
    $template->param(similarRecList=>$similarRecList);

    my $infoMsgMap            =loc_getMsgFile('/search/recDetailPage.msg');
    loc_write($template,$infoMsgMap);
    return $template->output;

}
#=======================================================
sub rinfo_getRatingInfoHTML{
    my($dbh,$rid)=@_;
    my $ratingInfo =getRatingInfo($dbh,$rid);
    my $rootDir   = Opals::Context->config('rootDir');
    my $template = _getTemplate("/htdocs/theme/opals/search/","ratingInfo.inc");
    foreach my $v(keys %$ratingInfo){
        $template->param($v=>$ratingInfo->{$v});
    }
    my $infoMsgMap            =loc_getMsgFile('record/rating_info.msg');
    loc_write($template,$infoMsgMap);
    return $template->output;

}

#=======================================================
sub getRatingInfo{
    my($dbh,$rid)=@_;
    my  $rating         =Opals::Context->preference('rating');
    my $reviews =  cmntRating_getInfoByRid($dbh,$rid);
    my $totalAccepted  = $reviews->{'totalAccepted'} ;
    my $avgRating = $reviews->{'avgRating'};
    my $numOfStars =floor($avgRating);
    my $fraction= $avgRating - $numOfStars ; 
    if($fraction >0.25 && $fraction<0.75){
        $numOfStars += 0.5;
    }
    elsif($fraction >0.75){
        $numOfStars += 1;
    }

    my $avgRating = sprintf("%.2f", $avgRating);
    return {
         rating     => $rating,
         rateRec    => $avgRating,
         totalAccepted  => $totalAccepted  ,
         numOfStars => $numOfStars,
         rid        => $rid,
        };

}

#=======================================================
sub getBookCover{
    my($rec,$size,$caption)=@_;
    my  $awsId =Opals::Context->preference('amazonId');
    my  $awsSecretKey =Opals::Context->preference('amazonSecreteKey');
    my  $syndeticsId =Opals::Context->preference('syndeticsId');
    if($syndeticsId ne''){
        bookCover_syndetics($rec,$size,$caption);
    }
    elsif($awsId ne '' && $awsSecretKey ne ''){
        bookCover_amazon($rec,$awsId,$awsSecretKey);
    }
    else{
        $size='m' if($size eq 'mc');
        bookCover_google($rec,$size);
    }

}


#=======================================================
sub getRecFilePath {
    my ($rid) = @_;
    
    my $zRoot   = Opals::Context->config('zRoot');
    my $zPort   = Opals::Context->config('zPort');
    my $zDatabase = Opals::Context->config('zDatabase');
    my $dir     = "$zRoot/$zPort/record/$zDatabase/" . ceil($rid/1000);

    return "$dir/$rid.xml";
}

#======================================================================
sub pf_getPfHTML{
    my ($dbh,$pfId,$op)=@_;
    my $template = _getTemplate("/htdocs/theme/opals/pf/","pfContHTML.inc");
    if($pfId && $pfId>0){
        my $pf=pf_getRecById($dbh,$pfId);
        if($pf){
            my $pfRec=pf_parsePfXml($pf->{'xml'});
            # change name od field title and author of thte pathfinder to fix the 
            # global var problem in template.
            $pfRec->{'title_pf'}=$pfRec->{'title'};
            $pfRec->{'author_pf'}=$pfRec->{'author'};
            $pfRec->{'title'}=undef;
            $pfRec->{'author'}=undef;


            my $isbnList="";
            my $bookRsList = $pf->{'bookRsList'};
            my @availBookRs=();
            my $i=0;
            my $indexConfFile  = Opals::Context->config('sIndexConfig');
            my $marcXmlParser=Opals::MarcXmlParser->new($indexConfFile) ;
            foreach my $bookRs(@{$pfRec->{'libraryRsList'}}){
                my $bookRsArr=[];
                foreach my $b (@{$bookRs->{'bookList'}}){
                    my $callnum1St      =util_restoreLiteral($b->{'callNumber'});
                    if($b->{'rid'}>0 && (defined $op && $op->{'circStats'}==1)){
                        my $rid=$b->{'rid'};
                        my $fname=getRecFilePath($rid);
                        my $cmntNote=$b->{'commentNote'};
                        $b=$marcXmlParser->getRecInfoGeneral_file($fname);
                        if (defined $b && $b->{'title'}) {
                            my $circStats       = circ_getRecCircStatus($dbh, $b->{'rid'});
                            $b->{'numTotal'}    = $circStats->{'totalHolding'};;
                            $b->{'numLoan'}     = $circStats->{'onLoan'};
                            $b->{'numReserve'}  = $circStats->{'onReserve'};
                            $b->{'numHold'}     = $circStats->{'onHold'};
                            $b->{'numReserveTotal'} = $circStats->{'onReserve'} + $circStats->{'onHold'};
                            $b->{'numAvailable'} = $circStats->{'available'};
                            $b->{'pubPlace'} = $b->{'placePublication'};
                            $b->{'pubName'} = $b->{'namePublisher'};
                            $b->{'pubDate'} = $b->{'datePublication'};
                            $b->{'commentNote'} = $cmntNote;

                            $b->{'title'} =~ s/(\.|\s)+$//g;
                            $b->{'subtitle'} =~ s/(\.|\s)+$//g;


                        }#END IF
                    }
                   else{
                        if(defined $b->{'isbnList'} && $b->{'isbnList'} ne ''){
                            my @isbnArr= split(/,/,$b->{'isbnList'});
                            if(scalar(@isbnArr)>0){
                                $b->{'isbn_first'} =@isbnArr[0];
                            }                
                        }
                        $b->{'isbn'}=[];
                    }
                    $b->{'callnum1St'}=$callnum1St if(defined $callnum1St && $callnum1St ne '');
                    $b->{'showBookCover'} =1 if(defined $op && $op->{'bookCover'}==1);               
                }
                getBookCover($bookRs->{'bookList'}) if(defined $op && $op->{'bookCover'}==1);

            }
                   
           $template->param(
                pf          => $pfRec,
                pfId        => $pfRec->{'pfId'},
                title_pf    => $pfRec->{'title_pf'},
                author_pf   => $pfRec->{'author_pf'},
                audience    => $pfRec->{'audience'},
                createdDate => $pfRec->{'createdDate'},
                #intro       => $pfRec->{'intro'} if($pfRec->{'intro'}) ,
                subject     => $pfRec->{'subject'},
                );

                
             $template->param(intro       => $pfRec->{'intro'})         if($pfRec->{'intro'});
             $template->param(libRsList   => $pfRec->{'libraryRsList'}) if($pfRec->{'libraryRsList'}); 
             $template->param(webRsList   => $pfRec->{'internetRsList'})if($pfRec->{'internetRsList'}); 
             if($pfRec->{'wSheetRsList'}){
                 foreach my $wsBlock(@{$pfRec->{'wSheetRsList'}}){
                     foreach my $ws(@{$wsBlock->{'wsList'}}){
                        if($ws->{'fRealName'} =~ m/(.*)\.([\w\-]+)$/g){
                            $ws->{'fileIcon'} =FILE_ICON->{lc($2)} if(FILE_ICON->{lc($2)});
                        }
                     }
                 }
             }
             $template->param(wsRsList    => $pfRec->{'wSheetRsList'})  if($pfRec->{'wSheetRsList'}); 
            # $template->param( showBookCover   =>1) if(defined $op && $op->{'bookCover'}==1);
             $template->param( showAnchor_lib  =>1) if(ref($pfRec->{'libraryRsList'})  eq 'ARRAY' && scalar(@{$pfRec->{'libraryRsList'}})>1);
             $template->param( showAnchor_web  =>1) if(ref($pfRec->{'internetRsList'}) eq 'ARRAY' && scalar(@{$pfRec->{'internetRsList'}})>1);
             $template->param( showAnchor_ws   =>1) if(ref($pfRec->{'wSheetRsList'})   eq 'ARRAY' && scalar(@{$pfRec->{'wSheetRsList'}})>1);
        }
    }
    $template->param(showImg     => ($op->{'showImg'} )?1:0);
    $template->param(showBibChk  => ($op->{'showBibChk'} )?1:0);
    $template->param(host=>$ENV{'SERVER_NAME'});
    my $msgValMap ={};
    my $msgMap            =loc_getMsgFile('util/pathfinder.msg',$msgValMap);
    loc_write($template,$msgMap);

    return $template->output;
}

#======================================================================
sub marc21_getMarcRec{
    my ($dbh,$rid,$op)=@_;
    my $template = _getTemplate("/htdocs/theme/opals/marc21/","MarcCont.inc");
    if($rid && $rid>0){
        my $marcxml="";
        my $path = getRecFilePath($rid);

        open RECORD, "<$path";
        my $line;
        while (<RECORD>) {
            $line = $_;
            if ($line =~ m/<subfield code="-">/) {
                next;
            }

            $marcxml .= $line;
        }
        close RECORD;

        my @rec = mc21_parseRecord($marcxml);
        $template->param(
            rec => \@rec,
        );
    }
    else {
        $template->param(
            error => 1,
        );
    }

    return $template->output;
}


#======================================================================
sub getReserveShelfHTML{
    my ($dbh,$shelfId,$op)=@_;
    my $template = _getTemplate("/htdocs/theme/opals/rs/","rsContHTML.inc");
    my $sr=undef; 

    if($shelfId && $shelfId>0){
       my $rec =rs_getReserveShelfByID($dbh,$shelfId,$op->{'sortBy'});
 
    #open debug,">/tmp/ssjson"; print debug to_json($rec,{pretty=>1}); close debug;
            $rec->{'reserveFrom'} = substr($rec->{'reserveFrom'},0,10);
            $rec->{'reserveTo'}   =  substr($rec->{'reserveTo'},0,10);
            
            foreach my $g (@{$rec->{'rsList'}}){
                foreach my $b(@{$g->{'itemList'}}){
                    my $callnum1St      =$b->{'callNumber'};
                    if(defined $op && $op->{'circStats'}==1){
                        my $rid=$b->{'rid'};
                        if (defined $b && $b->{'title'}) {
                            my $circStats       = circ_getRecCircStatus($dbh, $b->{'rid'});
                            $b->{'numTotal'}    = $circStats->{'totalHolding'};;
                            $b->{'numLoan'}     = $circStats->{'onLoan'};
                            $b->{'numReserve'}  = $circStats->{'onReserve'};
                            $b->{'numHold'}     = $circStats->{'onHold'};
                            $b->{'numReserveTotal'} = $circStats->{'onReserve'} + $circStats->{'onHold'};
                            $b->{'numAvailable'} = $circStats->{'available'};
                        }#END IF
                    }
                    else{
                        if(defined $b->{'isbnList'} && $b->{'isbnList'} ne ''){
                            my @isbnArr= split(/,/,$b->{'isbnList'});
                            if(scalar(@isbnArr)>0){
                                $b->{'isbn_first'} =@isbnArr[0];
                            }                
                        }
                        $b->{'isbn'}=[];
                    }
                    $b->{'callnum1St'}=$callnum1St if(defined $callnum1St && $callnum1St ne '');                    
                    $b->{'showBookCover'}=1 if(defined $op && $op->{'bookCover'}==1);
                }
                getBookCover($g->{'itemList'})if(defined $op && $op->{'bookCover'}==1) ;
            }
            push @$sr,$rec;
    }
     $template->param(sr =>$sr );
    

    $template->param(showUserList=> (defined $op->{'showUserList'} && $op->{'showUserList'} )?1:0);
    $template->param(showImg     => ($op->{'showImg'} )?1:0);
    $template->param(showBibChk  => ($op->{'showBibChk'} )?1:0);
    $template->param(uDisplay    => (defined $op->{'uDisplay '} && $op->{'uDisplay'}>0 )?1:0);
    $template->param(host=>$ENV{'SERVER_NAME'});
    my $msgValMap ={};
    my $msgMap            =loc_getMsgFile('util/reserveShelf.msg',$msgValMap);
    loc_write($template,$msgMap);

    return $template->output;
}
#===========================================================
sub getRelGenreList{
    my ($dbh,$rid)=@_;
    my $gList=[];
    my $sth=$dbh->prepare("select distinct gId,title,author,introduction  from opl_genre g inner join opl_genreItems i using(gId) where rid=?");
    $sth->execute($rid);
    while(my $g=$sth->fetchrow_hashref){
        push @$gList,$g;
    }
    return $gList;
}

#======================================================================
