#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use Digest::SHA qw(
    sha1_base64
    sha1_hex
);

use Opals::Context;
use Opals::Template_ajax qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);
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, $cookie, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'ajax/portlet/getLibHours.tmpl',
        
    }
);

my $msgValMap ={};
    my $stdMsgMap            =loc_getMsgFile('util/lHours.msg',$msgValMap);
    my $openingHours = listOpeningHr($dbh);
    foreach my $oh(@$openingHours){
        $oh->{'weekday'}=$stdMsgMap->{'weekday_' .$oh->{'weekday'}};
        $oh->{'openPeriod'}=scalar(@{$oh->{'hours'}});
    }
    $template->param(
        openingHours => $openingHours,

    );
    loc_write($template,$stdMsgMap);

 
tmpl_write($dbh, $cgi, $cookie, $template);
################################################################################
sub listOpeningHr{
    my ($dbh) = @_;
    
    my $sth = $dbh->prepare(<<_STH_);
    select weekday,open,close from  opl_openHours order by weekday,id 
_STH_
    $sth->execute;
 
    my @oHoursList;
    my $preWd=-1;
    my $i=-1;my $j=0;

    while (my ($wd,$open,$close) = $sth->fetchrow_array) {
         $open = mil2AmPmTime($open);
         $close = mil2AmPmTime($close);
         if($wd !=$preWd){
             my @h=({'open'=>$open,'close'=>$close});
             push @oHoursList,{'rowIndex'=>$j%2,nPeriod=>1,weekday=>$wd,hours=>\@h};
             $i++; 
             $preWd=$wd;
         }
         else{
             push @{@oHoursList[$i]->{'hours'}},{'open'=>$open,'close'=>$close};
         }
         @oHoursList[$i]->{'nPeriod'}=scalar(@{@oHoursList[$i]->{'hours'}});
         ++$j;
    }
    $sth->finish;
    return \@oHoursList;

}
################################################################################
sub mil2AmPmTime{
    my ($time)=@_;
    return $time if($time !~ m/[\d]{1,2}:[\d]{1,2}/g);
    my $amPm ="AM";
    my @hr=split(':',$time);
    if(@hr[0]>=12){
        $amPm="PM";
        @hr[0] -=12 if(@hr[0]>12);
    }
    return sprintf("%02d:%02d %s",@hr[0],@hr[1],$amPm);

}

#------------------------------------------------------------------------------



