#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Opals::Context;
use Opals::Constant;
use Date::Calc::Object qw(
    :all
);
use Time::localtime;

use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);
use Opals::User qw(
    user_currentUser
    user_permission
    user_permission_1
    user_StrPermission
    user_StrPermission_1

);
use Opals::Circulation qw(
    eCirc_isOnLoanTo
    circ_getRecCircStatus_ebook
);

use Opals::Date qw(
 date_text
 );
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);
use Opals::Ebook qw(
    eb_getLicense
);
use Opals::WebServiceEbookClient qw( 
    wsc_getEbook
);

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

my $cgi = CGI->new;
my $input = $cgi->Vars();
my $bid=$input->{'bid'};
my $rdrStyle=$input->{'style'};
if(!$rdrStyle){
    $rdrStyle='standard';
}
my ($permission, $cookie, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'ebook/reader.tmpl',
        }
);

my ($errCode, $cookie, $user) = user_currentUser($dbh, $cgi);
my ($uid,$authorized,$mod)=(0,0,'book');
my $username =$cgi->param('username');


my $circStatus= circ_getRecCircStatus_ebook($dbh,$bid);
my $isFreeBook=($circStatus && $circStatus->{'ebookLicType'} eq 'free');
if($errCode==0){
    $uid =$user->{'uid'};
    $authorized=(eCirc_isOnLoanTo($dbh,$uid,$bid) || $permission->{'ebook_mgmt'} );
}
$authorized =( $authorized || $isFreeBook);
#if($loginuid){
 
    my $params={bid=> $bid};
    my $ebook = wsc_getEbook($params);

    my $toc = $ebook->{'TOC'};
    my $title = $ebook->{'metadata'}->{'title'};
    my $author= $ebook->{'metadata'}->{'author'};
    my $spine=$ebook->{'spine'};
    #push @$spine,{spineItem =>EBOOK_EOB};

    my $bmList = getBookmark($dbh,$uid,$bid);
    my $bShelf = getBookShelves($dbh,$uid);
    $template->param(bid                =>$bid,
                     title              =>$title,
                     author             =>$author,
                     spine              =>$spine,
                     toc                =>$toc,
                     username           =>$username,
                     uid                =>$uid,
                     readerAuthorized   =>$authorized,
                     bmList             =>$bmList,
                     bShelf             =>$bShelf,   
                     EBOOK_EOB          =>EBOOK_EOB,
                     rdrStyle           =>$rdrStyle,
                     isFreeBook         =>$isFreeBook);
#}
my $ebookMsgMap        =loc_getMsgFile('ebook.msg',{});
loc_write($template,$ebookMsgMap);
tmpl_write($dbh, $cgi, $cookie, $template);

################################################################################
sub getBookmark{
    my ($dbh,$uid,$bid)=@_;
    my $sth=$dbh->prepare("select distinct b.* from eb_bookmark b where uid=? && b.bid =? order by b.percFr");
    $sth->execute($uid,$bid);
    my @bmList;
    while(my $rec = $sth->fetchrow_hashref){
        #$rec->{'bmDate'} = date_text($rec->{'bmDate'},0);
        push @bmList, $rec;
    }
    $sth->finish;
    return \@bmList; 

}
########################################################################################
sub getBookShelves{
    my ($dbh,$uid)=@_;
    my $sth=$dbh->prepare("select s.rid,s.bsId , r.title as bTitle ,m.bid  from eb_bookshelves s inner join opl_ridBid m using(rid) inner join opl_marcRecord r using(rid)  where uid=? order by bsId");
                          
    $sth->execute($uid);
    my @bsList;
    my $accessable=0;
    while(my $rec = $sth->fetchrow_hashref){
        my $ebLicense = eb_getLicense($dbh,$rec->{'bid'});
        if($ebLicense->{'licenseType'} eq 'free'){
            $accessable=1;
        }
        else{
            $accessable=eCirc_isOnLoanTo($dbh,$uid,$rec->{'bid'});
        }
        $rec->{'accessable'} = $accessable;
        push @bsList, $rec;
    }
    $sth->finish;
    return \@bsList; 
}

################################################################################

sub getBook{
    my ($dbh,$bid)=@_;
    my $sth=$dbh->prepare("select title,author from eb_record where bid=?");
    $sth->execute($bid);
    if(my ($title,$author)=$sth->fetchrow_array){
        return ($title,$author);
    }
    return (undef,undef);
    
}
################################################################################

sub getBookToc{
    my ($dbh,$bid)=@_;
    my $sth=$dbh->prepare("select * from eb_toc where bid=? order by playOrder");
    $sth->execute($bid);
    my $toc=[];
    while(my $rec=$sth->fetchrow_hashref){
        push @$toc,$rec;
    }
    return $toc;
    
}
################################################################################
sub getBookSpine{
    my ($dbh,$bid)=@_;
    my $sth=$dbh->prepare("select fid spineItem from eb_spine where bid=? order by playOrder");
    $sth->execute($bid);
    my $spine=[];
    while(my ($fid)=$sth->fetchrow_array){
        push @$spine,{spineItem=>"/ebook/$bid/$fid"};
    }
    return $spine;
    
}
################################################################################

sub isAuthorized{
    my($dbh,$uid,$bid)=@_;
    my $auth=0;
    my $sth =$dbh->prepare(<<_STH_);
select  l.* from opl_ridBid e 
        inner join opl_ebLoan l using(bid) 
where   e.bid=? && uid=? && l.dateReturn >now()
_STH_

    $sth->execute($bid,$uid);
    if(my $rec = $sth->fetchrow_hashref){
        $auth=1;
    }
    return $auth;
}

################################################################################

