var fs=require("fs");
var settings=require("../settings");
var glob = require("glob");
var system = require('../../base/system');
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){
	if(bizcompCache[compname] && settings.env=="prod"){
		return bizcompCache[compname];
	}else{
		var htmlpath=settings.basepath+"/app/front/vues/pages/"+compname+"/"+compname+".html";
		var jspath=settings.basepath+"/app/front/vues/pages/"+compname+"/"+compname+".js";

		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[compname]=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);
		});
	});
};
