const fs=require("fs");
const path=require("path");
const appsPath=path.normalize(__dirname+"/apps");
const bizsPath=path.normalize(__dirname+"/bizs");
var appJsons={

}
function getBizFilePath(appJson,bizCode){
  const filePath=bizsPath+"/"+"bizjs"+"/"+bizCode+".js";
  return filePath;
}
//异常日志处理todo
function initAppBizs(appJson){
    for(var bizCode in appJson.config.bizs)
    {
      const bizfilePath=getBizFilePath(appJson,bizCode);
      try{
        delete require.cache[bizfilePath];
        const bizConfig=require(bizfilePath);
        appJson.config.bizs[bizCode].config=bizConfig;
      }catch(e){
        // console.log("bizconfig meta file not exist........");
      }

    }
    return appJson;
}
//初始化资源树--objJson是rstree
function initRsTree(appjson,appidfolder,objJson,parentCodePath){
  if(!parentCodePath){//说明当前是根结点
    objJson.codePath=objJson.code;
  }else{
    objJson.codePath=parentCodePath+"/"+objJson.code;
  }
  if(objJson["bizCode"]){//表示叶子节点
    objJson.auths=[];
    if(appjson.config.bizs[objJson["bizCode"]]){
      objJson.bizConfig=appjson.config.bizs[objJson["bizCode"]].config;
      objJson.path=appjson.config.bizs[objJson["bizCode"]].path;
      appjson.config.bizs[objJson["bizCode"]].codepath=objJson.codePath;
    }
  }else{
    if(objJson.children){
      objJson.children.forEach(obj=>{
        initRsTree(appjson,appidfolder,obj,objJson.codePath);
      });
    }
  }
}
fs.readdirSync(appsPath).forEach(f=>{
    const ff=path.join(appsPath,f);
    delete require.cache[ff];
    var  appJson=require(ff);
    appJson=  initAppBizs(appJson);
    initRsTree(appJson,appJson.appid,appJson.config.rstree,null);
    appJsons[appJson.appid]=appJson;
});
module.exports=appJsons;
