var fs=require("fs");
var settings=require("../settings");
var glob = require("glob");
var system = require('../../base/system');
var cacheManager=system.getObject("db.cacheManager");
var bizcompCache={};
async function asycReadFile(path){
   var p=new Promise(function(reslv,reject){
        fs.readFile(path,function(err,r){
           if(err){
              reject(err);
           }else{
              reslv(r);
           }
        });
   });
   return p;
}
async function buildComponent(compname,themeQuery,hostname){
	//按照hostname获取主题
	var themename=await cacheManager["ThemeCache"].cacheTheme(hostname);
	if(themeQuery!=""){
		themename=themeQuery;
	}
	var cachecomname="";
	if(themename && themename!="" && themename!="undefined" && themename!="default"){
		 cachecomname=themename+"_"+compname;
	}else{
		cachecomname=compname;
	}

	if(bizcompCache[cachecomname] && settings.env=="prod"){
		return bizcompCache[cachecomname];
	}else{
		var htmlpath=settings.basepath+"/app/front/vues/pages/"+compname+"/"+compname+".html";
		var jspath=settings.basepath+"/app/front/vues/pages/"+compname+"/"+compname+".js";
		if(themename && themename!=""){
			 var tmphtmlpath=settings.basepath+"/app/front/vues/pages/"+compname+"/"+themename+"/"+compname+".html";
		    var tmpjspath=settings.basepath+"/app/front/vues/pages/"+compname+"/"+themename+"/"+compname+".js";
			 if(fs.existsSync(tmphtmlpath)){
				htmlpath=tmphtmlpath;
				jspath=tmpjspath;
			 }

		}
		var html=  await asycReadFile(htmlpath);
		var tmpl=html.toString("utf-8");
		var js=    await asycReadFile(jspath);
		var jsstr=js.toString("utf-8");
		jsstr=jsstr.replace("${tmpl}",tmpl);
		bizcompCache[cachecomname]=jsstr;
		return jsstr;
	}

}
module.exports = function (app) {
	app.get('/vue/comp/base',function(req,res){
		var vuePath=settings.basepath+"/app/front/vues/base";
		var baseComps=[];
		var rs=glob.sync(vuePath+"/**/*.vue");
		if(rs){
			rs.forEach(function(r){
				var comp="";
				if(settings.env=="dev"){
					 delete require.cache[r];
					 comp=require(r).replace(/\n/g,"");
				}else{
					 comp=require(r).replace(/\n/g,"");
				}
				baseComps.push(comp);
			});
			res.end(JSON.stringify(baseComps));
		}
	});
	app.get('/vue/comp/:cname',function(req,res){
		var componentName=req.params.cname;
		var theme=req.headers["theme"];
		var hostname=req.hostname;
		buildComponent(componentName,theme,hostname).then(function(r){
			res.end(escape(r.replace(/\n/g,"")));
			// res.end(r);
		});
	});
};
