package Opals::Locale;

require Exporter;
@ISA       = qw(Exporter);
# Symbols to be exported by default
#@EXPORT    = qw(
#    opl_
#);
# Symbols to be exported on request
@EXPORT_OK = qw(
    loc_getMsgFile
    loc_setMsgValue
    loc_write
    
);
# Version number
$VERSION   = 0.01;


use Opals::Context;
#use utf8;
use strict;
#use Opals::_Some_Module_;


########################################################################################
sub loc_getMsgFile {
    my ($msgFile,$valMap) = @_;
    my $lang =$ENV{'curLang'};


    $lang='en' if(!defined $lang || $lang eq '');

    my $rootDir = Opals::Context->config('rootDir');

    my $msg = {};
    my $file="$rootDir/htdocs/theme/opals/locale/en/$msgFile";
    open MSG, $file || die "Cannot open file $msgFile";

    while (<MSG>) {
        chomp;
        next if /^\s*$/;        # ignore blank lines
        if (/^\s*(\w+)\s*=\s*(.*?)\s*$/) {
            $msg->{$1} = $2;
        }
    }
    close MSG;
    if($lang ne 'en'){
        $file="$rootDir/htdocs/theme/opals/locale/$lang/$msgFile";
        open MSG, $file || die "Cannot open file $msgFile";
        while (<MSG>) {
            chomp;
            next if /^\s*$/;        # ignore blank lines
            if (/^\s*(\w+)\s*=\s*(.*?)\s*$/) {
                $msg->{$1} = $2;
            }
        }
    }
    if($valMap){
        foreach my $msgKey(keys %{$msg}){
             if($valMap->{$msgKey}){
                $msg->{$msgKey} =loc_setMsgValue($msg->{$msgKey},$valMap->{$msgKey});
            }
        }
    }

    return $msg;
}
########################################################################################
sub loc_getMsgFile_bk {
    my ($msgFile,$valMap) = @_;
    my $lang =$ENV{'curLang'};


    $lang='en' if(!defined $lang || $lang eq '');

    my $rootDir = Opals::Context->config('rootDir');
    my $file="$rootDir/htdocs/theme/opals/locale/$lang/$msgFile";

    my $msg = {};
    open MSG, $file || die "Cannot open file $msgFile";

    while (<MSG>) {
        chomp;
        next if /^\s*$/;        # ignore blank lines

        if (/^\s*(\w+)\s*=\s*(.*?)\s*$/) {
            my $msgKey=$1;
            my $msgVal=$2;
            if($valMap && $valMap->{$msgKey}){
                $msgVal =loc_setMsgValue($msgVal,$valMap->{$msgKey});
            }
            $msg->{$msgKey} = $msgVal;
        }
    }
    close MSG;
    return $msg;
}

########################################################################################

sub loc_setMsgValue {
    my ($msgStr, $valMap) = @_;
    my $retMsg;
    while(my($key, $value) = each(%$valMap)){
        my $var="#{$key}";
        $msgStr =~ s/$var/$value/gi;
    }
    return $msgStr;
}

########################################################################################
sub loc_write{
    my($template,$msgMap)=@_;

    while(my($key, $value) = each(%$msgMap)){
        $template->param($key => $value );
    }


}


1;
