#!/usr/bin/perl
use Opals::Context;
use Time::localtime;
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);
use Opals::Date qw(
    date_parse
    date_text
    date_profileList
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);


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

my $cgi = CGI->new;
my ($permission, $cookieList, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'lHours.tmpl',
        }
);

    my $tm = localtime;
    my $dateToday = sprintf("%04d-%02d-%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday);



   my ($openingHours) = listOpeningHr($dbh);
   my $msgValMap ={};
    my $stdMsgMap            =loc_getMsgFile('util/lHours.msg',$msgValMap);
    my $openingHours = listOpeningHr($dbh);
    my $oddEven=0;
    foreach my $oh(@$openingHours){
        $oddEven=$oddEven?0:1;
        $oh->{'odd'}=$oddEven;
        $oh->{'weekday'}=$stdMsgMap->{'weekday_' .$oh->{'weekday'}};
        $oh->{'openPeriod'}=scalar(@{$oh->{'hours'}});
    }
   $template->param(
         openingHours  => $openingHours, hlpUrl     => Opals::Constant->getHlpUrl("lHours")
   );

#Thu, Jan 07, 2010 @ 14:03:38 EST
my $msgValMap ={};
my $stdMsgMap            =loc_getMsgFile('util/lHours.msg',$msgValMap);
loc_write($template,$stdMsgMap);

tmpl_write($dbh, $cgi, $cookie, $template); 
#######################################
sub listOpeningHr{
    my ($dbh) = @_;
    
    #select * from  opl_openHours where open1<>'' or open2<>'' order by id
    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};
         }
    }
   
=item
    while (my $rec = $sth->fetchrow_hashref) {
         push @oHoursList, $rec;
    }
=cut
    
    $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);

}

