#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use JSON;
use Opals::Context; 
my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }
my $userTypeInfo ={};
if ($ENV{'REQUEST_METHOD'} eq "POST") {
    my $json ="";
    while (<STDIN>) {
        $json .= $_;
    }
    $userTypeInfo = decode_json($json);

    $userTypeInfo =saveUserType($dbh,$userTypeInfo);
    
}

print "Content-type: text/plain\n\n";
print  to_json($userTypeInfo,{pretty => 1});
#===================================================================================================
sub saveUserType{
    my ($dbh,$userTypeInfo)=@_;
    my @fList=();
    my @fData=();
    my $catid=0;
    if(defined $userTypeInfo->{'catid'} && $userTypeInfo->{'catid'} >0){
        $catid =$userTypeInfo->{'catid'};
    }
  
    foreach my $f(qw(catname allowUserEdit maxloans maxreserv maxOverdue accBalThreshold required allowAccessMyFile authenticateBySID defaultPerm keepLoanHistory)){
        if(defined $userTypeInfo->{$f}){
            push @fList,"$f=? ";
            push @fData,$userTypeInfo->{$f};
        }
    }
    my $sql="";
    if($catid>0){
        my ($oldPerm)=$dbh->selectrow_array("select defaultPerm from opl_category where catid=$catid");
        my $newPerm=$userTypeInfo->{"defaultPerm"};
        $sql ="update opl_category set " . join(",",@fList) . " where catid= $catid" ;
        updateExitedUserPerm($dbh,$catid,$oldPerm,$newPerm);
    }
    else{
        $sql="insert into opl_category set " .  join(",",@fList);
    }
    my $sth= $dbh->prepare($sql);
    $sth->execute(@fData);
    if($catid==0){
        $userTypeInfo->{'catid'}=$dbh->{'mysql_insertid'};
    }
    $sth->finish;
    return $userTypeInfo;
}
#===================================================================================================
sub updateExitedUserPerm{
    my ($dbh,$catid,$oldPerm,$newPerm)=@_;

    my @oArr=split(",",$oldPerm);
    my @nArr=split(",",$newPerm);

    my $sth_update=$dbh->prepare("update opl_user set permissions=? where uid=? && uid<>1 && (username is not null && username <>'')");
    my $sth=$dbh->prepare("select uid,permissions from opl_user where categorycode=? 
                          && permissions is not null && permissions <>'' && permissions <> ?");
    $sth->execute($catid,$oldPerm);
    my $newPermStr="";
    while( my ($uid,$perm)=$sth->fetchrow_array){
        my @pArr=split(",",$perm);
        @pArr=getAComplementB(\@pArr,\@oArr);
        @pArr=getAComplementB(\@pArr,\@nArr);
        @nArr =(@nArr,@pArr);
        @nArr =sort @nArr;
        $newPermStr=join ",",@nArr;
        $sth_update->execute($newPermStr,$uid);
    }
    $sth_update= $dbh->prepare("update opl_user set permissions=? where uid<>1 && categorycode=? && 
                 (permissions = ? || permissions ='' || permissions is null)");
   $sth_update->execute($newPerm,$catid,$oldPerm);
      
}
#===================================================================================================
sub getAComplementB{
    my($A,$B)=@_;
    my %C = map {$_ => 1} @$B;
    my @C =  grep {not $C{$_}} @$A;
    return @C;
}
#===================================================================================================
