#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Opals::Context;use POSIX;

use Date::Calc qw(Day_of_Week Week_Number Day_of_Year);

use Opals::User qw(
    user_getInformation
    user_getInformationById
    user_balance
    user_paid
    user_paymenthistory
);

use Opals::Circulation qw(
    circ_userListLoan
    eCirc_getUserLoanList
);


use Opals::Date qw(
    date_parse
    date_today
    date_text
);
use Opals::SolrIndex qw(
    slr_eb_buildSearchQuery
    slr_eb_search
);
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference
    tmpl_rangedPageList
);

use Opals::Circulation qw(
    circ_getRecCircStatus
);
use Opals::User qw(
    user_currentUser
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);
use Opals::BookCover qw(
    bookCover_getUrl
    bookCover_amazon
    bookCover_google
    bookCover_syndetics

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

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

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

my ($permission, $cookie, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'user/myLibrary.tmpl',
#            reqPermission   => 'user_delete',
        }
);
my $lang=$template->param('curLang');
my $syspref = tmpl_preference($dbh);
my ($errCode, $myCookie, $user) = user_currentUser($dbh, $cgi);
my $bShelf = ();
if($errCode==0){
    my $uid = $user->{'uid'};    
    $bShelf = getBookShelves($dbh,$uid);
    $template->param(bShelf             =>$bShelf);
}




my $msgValMap ={};
my $msgMap            =loc_getMsgFile('user/userInfo.msg',$msgValMap);
loc_write($template,$msgMap);
my $msgMap            =loc_getMsgFile('ebook.msg',$msgValMap);
loc_write($template,$msgMap);

tmpl_write($dbh, $cgi, $cookie, $template);
########################################################################################
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; 
}

#////////////////////////////////////////////////////////////////////////////
 __END_OF_FILE:

