#!/usr/bin/perl

use strict;
use CGI;

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

use Opals::RecordInfoHTML qw(
    getReserveShelfHTML
);
use Opals::Mail qw(
    mail_send
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);

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        => 'rs/rsEmail.tmpl',
    }
);

my $pref    = tmpl_preference($dbh);

my $rsCont="";

my $sortBy=$input->{'sortBy'};
my $groupId=$input->{'groupId'};
my $shelfId     = $input->{'shelfId'};
my $to          = $cgi->param('email');
my $circStats   = $cgi->param('circStats'); 
my $bookCover   = $cgi->param('bookCover');
my $emailOpt={};
$emailOpt->{'groupId'}=  $groupId;
$emailOpt->{'sortBy'}=  $sortBy;
$emailOpt->{'circStats'}=1    if($input->{'circStats'} && $input->{'circStats'} eq 1);
$emailOpt->{'bookCover'}=1    if($input->{'bookCover'} && $input->{'bookCover'} eq 1);
$emailOpt->{'showUserList'}=1 if($input->{'showUserList'} && $input->{'showUserList'} eq 1);
$emailOpt->{'showBibChk'}=0;


#open debug ,">/tmp/bb"; print debug "$sortBy\n";close debug;
if(!$to){
        $template->param(
            shelfId     =>$shelfId,
            circStats   =>$circStats,
            bookCover   =>$bookCover,
            sortBy      =>$sortBy,
            groupId     =>$groupId,
            openForm    =>1,
            email       =>$to
       );

        $to =~ s/ +/,/g;
        $to =~ s/;+/,/g;
        $to =~ s/,+/,/g;
        $to =~ s/(^,|,$)//g;

    }
else{ 
    if($shelfId && $shelfId>0){
        $rsCont=getReserveShelfHTML($dbh,$shelfId,$emailOpt);
    }

    if ($rsCont ne '' && mail_send($pref, $to, 'Reserve Shelf', $rsCont)){
        $template->param(done=>1);
    }
    else{
        $template->param(error=>1);
    }
    $template->param(email=>$to );

my $msgValMap ={};
my $msgMap            =loc_getMsgFile('util/reserveShelf.msg',$msgValMap);
loc_write($template,$msgMap);

   $template->param(rsContent=>$rsCont,
                    showUserList=>$emailOpt->{'showUserList'});

}
   $template->param(showUserList=>$emailOpt->{'showUserList'});

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

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

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


