#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Opals::Context;
use Date::Calc qw(Day_of_Week Week_Number Day_of_Year);
use Date::Calc::Object qw(
    :all
);
use Time::localtime;

use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);

use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);
use Opals::Date qw(
    date_f005
);

use Opals::BookingSystem qw(
    bs_getBookingById_libCat
);

use Opals::Mail qw(
    mail_send
);

use Opals::BookCover qw(
    bookCover_getUrl
    bookCover_opals
);
################################################################################
my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $cgi = CGI->new;
my $input = $cgi->Vars();
my $dateToday = date_f005();
    $dateToday =~ s/([\d]{4})([\d]{2})([\d]{2})[\d]+\.(0|1)/$1-$2-$3/;
my $syspref          = tmpl_preference($dbh);

my $tm          = localtime;
my $todayStr    = sprintf("%04d-%02d-%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday);
my  $awsId =Opals::Context->preference('amazonId');
my  $awsSecretKey =Opals::Context->preference('amazonSecreteKey');
my  $syndeticsId =Opals::Context->preference('syndeticsId');
if($syndeticsId && $syndeticsId ne''){$awsId ="";}
my $op = $input->{'op'};
my ($permission, $cookie, $template);
my $bid = $input->{'selBid'};
my $bookingCont = getHTMLContent($dbh,$cgi,$bid,$op); 
if($op && $op eq 'email'){
    ($permission, $cookie, $template) = tmpl_read(
            {
                dbh             => $dbh,
                cgi             => $cgi,
                tmplFile        => 'circ/bEmail.tmpl' ,
                reqPermission   => 'circ_rsrv_self|circ_rsrv',
            }
    );
    my $pref    = tmpl_preference($dbh);
    my $from    = $pref->{'emailAddress'};
    my $smtp    = $pref->{'emailSmtp'};
    my $circulationSound = $pref->{'circulationSound'};

    my $to           = $cgi->param('email');
    my $subject      = $cgi->param('subject');
    if(!$to){
        $template->param(
            openForm    =>1,
            email       =>$to,
            subject     =>$subject,
            bookingId   => $bid
       );
    }
    else{
        $to =~ s/ +/,/g;
        $to =~ s/;+/,/g;
        $to =~ s/,+/,/g;
        $to =~ s/(^,|,$)//g;
       
        if (mail_send($pref, $to, $subject, $bookingCont)){
           $template->param(done=>1);
         }
        else{
           $template->param(error=>1);
        }
        $template->param(email=>$to );
   }
}
elsif($op && $op eq 'print'){
    ($permission, $cookie, $template) = tmpl_read(
            {
                dbh             => $dbh,
                cgi             => $cgi,
                tmplFile        => 'circ/bPrint.tmpl' ,
                reqPermission   => 'circ_rsrv_self|circ_rsrv',
            }
    );
}
else{
    ($permission, $cookie, $template) = tmpl_read(
            {
                dbh             => $dbh,
                cgi             => $cgi,
                tmplFile        => 'circ/bView.tmpl' ,
                reqPermission   => 'circ_rsrv_self|circ_rsrv',
            }
    );
    $template->param(prtNotice => 1);
}
my $loginuid         = $template->param('curUserId');
my @cookieList  = (@$cookie);

if ($permission && ($permission->{'circ_rsrv_self'}|| $permission->{'circ_rsrv'})){   
    if(!$op || $op eq 'view' || $op eq 'print'){
        $template->param(htmlBookingCont=>$bookingCont);
    }
}



    my $msgMap  = loc_getMsgFile('circ/booking.msg');
    loc_write($template,$msgMap);
tmpl_write($dbh, $cgi, \@cookieList, $template);

###############################################################################
sub getHTMLContent{
    my($dbh,$cgi,$bid,$op)=@_;
    my ($permission, $cookie, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'circ/bViewCont.inc',
        }
    );
    my $booking     = bs_getBookingById_libCat($dbh,$bid);
    my $itemList    = $booking->{'itemList'};
        my $isbnList=""; my $bibStr ="";
        foreach my $item(@$itemList){
            $item->{'numLoan'} =defined $item->{'loanList'}?scalar(@{$item->{'loanList'}}):0;
            #if($item->{'isbn'}){
            #    $isbnList .=   "," . $item->{'isbnList'} ;
            #}
            
            $bibStr = "";
            $bibStr = $item->{'author'};
            if($bibStr ne ''){
              $bibStr  .= ' ' ;
            }      
            $bibStr  .= '<b><u>' . $item->{'title'} . '</u></b>';
            if($item->{'pubPlace'} ne ''){
                $bibStr  .= ' ' . $item->{'pubPlace'};
                if($item->{'pubName'} ne ''){
                  $bibStr  .= ': ' . $item->{'pubName'};
                }
            }
            else{
                if($item->{'pubName'} ne ''){
                  $bibStr  .= ' ' . $item->{'pubName'};
                }
            }
            if($item->{'pubDate'} ne ''){
                $bibStr  .= ', ' . $item->{'pubDate'};
            }
            $item->{'bibStr'} = $bibStr;

        }
        bookCover_opals($itemList);

=item        
        if($isbnList ne ""  ){
            my $bookCoverUrls= bookCover_getUrl($isbnList,$awsId,$awsSecretKey);
            foreach my $item(@{$booking->{'itemList'}}) {
                foreach my $isbn(@{$item->{'isbn'}}){
                    if($bookCoverUrls->{$isbn}){
                        $item->{'bookcover'}=$bookCoverUrls->{$isbn}->{'small'};
                    }
                }
            }
        }
=cut        
        $template->param(
            bookingId           => $booking->{'bookingId'},
            status              => $booking->{'status'},
            reqUid              => $booking->{'reqUid'},
            department          => $booking->{'department'},
            course              => $booking->{'course'},
            reqFirstname        => $booking->{'reqFirstname'},
            reqLastname         => $booking->{'reqLastname'},
            reserveFrom         => $booking->{'reserveFrom'},
            reserveTo           => $booking->{'reserveTo'},
            startDate           => $booking->{'startDate'},
            startTime           => $booking->{'startTime'},
            endDate             => $booking->{'endDate'},
            endTime             => $booking->{'endTime'},
            itemList            => $booking->{'itemList'},
            reserve4UserList    => $booking->{'reserve4UserList'},
            #isbnList            => $isbnList,
            showAmazonCover     => ($awsId && $awsId ne '')  ?1:0,
            showSyndeticsCover  => ($syndeticsId && $syndeticsId ne '')  ?1:0,
            selfBooking         => scalar(@{$booking->{'reserve4UserList'}}),
        );
        if($op eq 'view'){
            $template->param(prtNotice => 1);
        }
    my $msgMap  = loc_getMsgFile('circ/booking.msg');
    loc_write($template,$msgMap);
    
    return $template->output;
}




