package Opals::Template_ajax;

use Exporter;
@ISA       = qw(Exporter);
# Symbols to be exported by default
#@EXPORT    = qw(
#    
#);
# Symbols to be exported on request
@EXPORT_OK = qw(
    tmpl_read
    tmpl_write
    tmpl_redirect
    tmpl_preference
);
#    $searchField
#    $sfIndex
# Version number
$VERSION   = 0.01;


use strict;

use HTML::Template;

use Opals::User qw(
    user_currentUser
    user_permission_1

);

my $lang='en';
###############################################################################



sub tmpl_preference {
    my ($dbh) = @_;
    my $preference;

    my $sth = $dbh->prepare(<<_STH_);
select  var, val
from    opl_preference
_STH_
    $sth->execute() || return;

    while (my ($var, $val) = $sth->fetchrow_array) {
        $preference->{$var} = $val;
    }
    $sth->finish;

    return $preference;
}



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

# return value:
# - 0: successful
# - 1: username missing
# - 2: username invalid
# - 3: password invalid
sub tmpl_read {
    my ($in) = @_;
   
    my ($dbh, $cgi, $tmplFile, $reqPermission, $tmplLocalVars, $op);
    $dbh            = $in->{'dbh'};
    $cgi            = $in->{'cgi'};
    $tmplFile       = $in->{'tmplFile'};
    $reqPermission  = $in->{'reqPermission'};
    $tmplLocalVars  = $in->{'tmplLocalVars'};
    $op             = $in->{'op'};
    my $sessionid = $cgi->cookie('sessionID');
    
   
    my @cookieList;
    my ($errCode, $user, $template);
    #my ($errCode, $cookie_session, $user, $template);
    my $permission;

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

    
 
    my $defaultLang=$pref->{'lang'};
    $defaultLang='en' if(!$defaultLang || $defaultLang !~ 'en|fr|es|pt|ar|ru');
    $lang = $cgi->cookie('language');
    if($lang !~ m/en|fr|es|pt|ar|ru/i){
        $lang          =$defaultLang;
    }
    $ENV{'curLang'}= $lang;
    my $theme='opals';
    ($theme && -X "$rootDir/$theme")       || ($theme   = 'opals');

    #######################################
    # Identify user
    my $ck;
    ($errCode, $ck, $user) = user_currentUser($dbh, $cgi);
    @cookieList = @{$ck} if $ck;

    undef $reqPermission if ($reqPermission eq 'none');

    #######################################
     
    if ($errCode==0) {
        $permission = user_permission_1($dbh, $user->{'uid'});
    }
    
     if ($reqPermission) {
        if (lc($reqPermission) eq 'required_login') {
            if (!$user) {
                $tmplFile = 'login.tmpl';
            }
        }
        elsif ($user) {
            if ($op) {
                if (!$permission->{$op}) {
                    $tmplFile = 'denied.tmpl';
                }
            }
            else {#($permission->{$reqPermission})
                my $granted = 0;
                foreach my $rp (split /\|/, $reqPermission) {
                    if ($permission->{$rp}) {
                        $granted = 1;
                        last;
                    }
                }
                if ($granted == 0) {
                    $tmplFile = 'denied.tmpl';
                }
            }
        }
        else {
            $tmplFile = 'login.tmpl';
        }
    }
    

    my $self = $ENV{'SCRIPT_NAME'};#(caller(0))[1];
    $template = HTML::Template->new(
        filename            => "$tmplFile",
        path                => "$rootDir/htdocs/theme/$theme",
        global_vars         => !$tmplLocalVars,
        die_on_bad_params   => 0,
        cache               => 1,
        shared_cache        => 0,
        loop_context_vars   => 1,
    );
    $template->param($pref);
    $template->param(curLang =>$lang, "lang_$lang"=>1);

 
   
    $template->param($permission);
  
    $ENV{'curUserId'}= $user->{'uid'};
    $template->param(
        template     => "/theme/$theme",
        curUserId    => $user->{'uid'},
        curUserName  => $user->{'username'},
        curFirstName => $user->{'firstname'},
    );
     
     
    foreach my $p (keys %$permission) {
        $template->param($p=>1);
        if ($p eq 'circ_rsrv_self' ){
            $template->param(
                rsrv_self =>1,
                );
        }
        if ($p eq 'circ_rsrv' || $p eq 'circ_loan' || $p eq 'circ_return' || $p eq 'circ_found' ){
            $template->param(
                circ =>1,
                );
        }
    }
 
    return ($permission, \@cookieList, $template);
}




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

sub tmpl_write {
    my ($dbh, $cgi, $cookie, $template) = @_;
    my $i=0;
    # Set system preferences
    my $pref = tmpl_preference($dbh);
    $template->param($pref);
     
    #IE doesn't recognize 'application/json' type, so change to 'text' seems to fix the problem for now.
    my($ua) = $ENV{HTTP_USER_AGENT};
    my $type="text/javascript";
    if (index($ua, "MSIE") > -1 || index($ua, "Trident") > -1 ) {
        $type="text";
    } 

    my $tmpl_output = $template->output;

    # AngularJS JSONP callback
    my $callback = $cgi->param('callback');
    if ($callback) {
      $tmpl_output = "$callback($tmpl_output);";
    }
      
    # Output
    print $cgi->header(
        #-type    => 'application/json', 
        #-type    => $type,
        -type     => 'text/plain',
        -expires => 'now',
        -cookie  => ($cookie)?$cookie:'',
        -charset => 'utf-8',
    ), $tmpl_output;
}

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

sub tmpl_redirect {
    my ($cgi, $script) = @_;

    print $cgi->redirect($script);
}


########################################################################
1;
