#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Opals::Context;
use Opals::Template 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 ($permission, $cookie, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'ajax/circ/libHours.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;
    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,{weekday=>$wd,hours=>\@h};
             $i++;
             $preWd=$wd;
         }
         else{
             push @{@oHoursList[$i]->{'hours'}},{'open'=>$open,'close'=>$close};
         }
    }
    $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);

}
#------------------------------------------------------------------------------
