import "ABAC.yjs";
module RBAC {
    function initRBAC(req, allRoles) {
        Global.allRoles = JSON.parse(allRoles);
        Global.roleTable = RocksDBUtil.loadDB("./roleTable", "false");
        initABAC(req);
    }
    function calculatePermission(roles) {
        var ret = [];
        for (var i = 0;
        i<roles.length;
        i++){
            var perms = Global.allRoles[roles[i]];
            if (perms!=null)
                ret = ret.concat(perms);
        }
        return ret;
    }
    @Description("{\"!user\":\"string\",\"!role\":\"string\"}")
    @ArgSchema({
    "!user":"string", "!role":"string"
    })
    @Access({
    "ACFunction":"accept"
    })
    export function addRole(arg) {
        if (Global.allRoles[arg.role]==undefined){
            YancloudUtil.exception({
            "code":500, "msg":"no such role"
            });
        }
        var arr = getRoleInternal(arg.user);
        if (arr.indexOf(arg.role)==-1){
            arr.push(arg.role);
            flushRole(arg.user, arr);
        }
        return arr;
    }

    @Description("两个参数， {\"user\":\"xxxx\", \"role\":\"\"}")
    @ArgSchema({
    "!user":"string", "!role":"string"
    })
    @Access({
    "ACFunction":"accept"
    })
    export function removeRole(arg) {
        if (Global.allRoles[arg.role]==undefined){
            YancloudUtil.exception({
            "code":500, "msg":"no such role"
            });
        }
        var arr = getRoleInternal(arg.user);
        var index = arr.indexOf(arg.role);
        if (index!=-1){
            arr.splice(index, 1);
        }
        flushRole(arg.user, arr);
        return arr;
    }

    function flushRole(user, roles) {
        Global.roleTable.put(user, JSON.stringify(roles));
        var permissions = calculatePermission(roles);
        flushPermission(arg.user, permissions);
    }

    @Description(" use signed request, no other arguments is required")
    @Access("verified")
    export function getMyRole(arg) {
        return getRoleInternal(requester);
    }

    function getRoleInternal(req) {
        var ret = Global.roleTable.get(req);
        if (ret==undefined) return [];
        return JSON.parse(ret);
    }
}