#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Opals::Constant;
use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);
use Opals::User qw(
    user_getInformationById
);
my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }
my $cgi = CGI->new;
my $input = $cgi->Vars();

my ($permission, $cookieList, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'record/setValLockRecPref.tmpl',
    }
);

my $loginuid = $template->param('curUserId');
my $syspref = tmpl_preference($dbh);
my $recLock = $syspref->{'recordLock'}; 
my $self = $ENV{'SCRIPT_NAME'};
my ($who,$where,$userInfo, $guardian);
if ($recLock ne ''){
    my @t= split(/,/,$recLock);   
    $who   =  @t[0];
    $where =  @t[1];
}

my $num=0;
if ($loginuid ne ''){
    if ($where eq '/bin/record/ge852') {
        $num = hasRequest($dbh);
        if ($num > 0) {
            updatePreference($dbh, $loginuid, 'scriptLock');
        }
        else {   # && ($who eq $loginuid) 
            updatePreference($dbh, $loginuid);
        }
    }
    elsif ( ($where eq '/bin/marc21/edit') && ($who eq $loginuid)){
        updatePreference($dbh, $loginuid);
    }
}
tmpl_write($dbh, $cgi, $cookieList, $template);

###################################################################
sub hasRequest{
    my ($dbh) = @_;

    my $numRequest =0;
    my $sth = $dbh->prepare(<<_SQL_);
select  count(req_id) as numReq 
from    opl_ge852request 
where   status in ('waiting', 'processing')
_SQL_
    $sth->execute();
    ($numRequest) = $sth->fetchrow_array; 
    $sth->finish;

    return $numRequest;
}

###################################################################
sub updatePreference {
    my ($dbh,$uid,$applName) = @_;

    if($applName){  
        my $val = $uid .','. $applName;
        my $sth = $dbh->prepare(<<_STH_);
update opl_preference 
set val= '$val'
where var = 'recordLock';
_STH_
        $sth->execute() ;
        $sth->finish;
    }
    else {
        my $sth = $dbh->prepare(<<_STH_);
update opl_preference 
set    val= NULL 
where var = 'recordLock';
_STH_
        $sth->execute() ;
        $sth->finish;
    }
}

