//#import Util.js
//#import $owl_orgs:services/modelService.jsx
//#import $owl_org_modules:services/modelService.jsx
//#import $owl_roles:services/modelService.jsx
//#import $owl_permission:services/modelService.jsx
//#import session.js
//#import $owl_backend_session:services/modelService.jsx

function getPermissions(roleId,tableId){
    var searchArgs = {
        roleId: roleId
    }
    var sr = owl_permissionService.search("0",searchArgs,null,0,10000,null);
    // $.log("getPermissions,roleId=" + roleId + ",tableId=" + tableId);
    if(sr.state==='ok'){
        // $.log("getPermissions,roleId=" + roleId + ",tableId=" + tableId + ", length=" + sr.list.length);
        return sr.list;
    }
    return [];
}

var appId = $.params.t;
if(!appId){
    var params = JSON.parse($body);
    appId = params.t;
}

var spec = $.getAppProgram(appId,"spec.json");


var isid = SessionService.getSessionId(request);
var sessionId = 'owl_backend_session_' + isid;

var session = owl_backend_sessionService.get(sessionId);
var roleId = session.roleId;
var rroleId = params.rroleId;
var roles = session.roles;
var userId = session.userId;
var orgId = session.orgId || "0";
var rorgId = params.rorgId;
var permissions = getPermissions(rroleId||roleId,appId);

if(spec){
    var specObj = JSON.parse(spec);
    var ret = {
        state:"ok",
        spec:specObj,
        permissions:permissions,
        roleId:rroleId || roleId,
        tableId:appId,
        appId:appId,
        userId:userId,
        userName:session.userName,
        orgId:rorgId || orgId
    }
    out.print(JSON.stringify(ret));
}
else{
    var ret = {
        state:"err",
        msg:"app not found!",
        appId:appId
    }
    out.print(JSON.stringify(ret));
}
