var fs = require("fs");
var settings = require("../settings");
var os = require("os");

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) {
	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);
	return jsstr;
}
module.exports = function (app) {
	app.get('/vue/comp/base', function (req, res) {
		var vuePath = settings.basepath + "/app/front/vues/base";
		var baseComps = [];
		fs.readdir(vuePath, function (err, rs) {
			if (rs) {
				rs.forEach(function (r) {
					delete require.cache[require.resolve(vuePath + "/" + r)];
					var comp = require(vuePath + "/" + 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;
		buildComponent(componentName).then(function (r) {
			let platform = os.platform() || "";
			console.log(platform, '----------------');
			// windows
			if (platform.toLocaleLowerCase().startsWith('win')) {
				res.end(r.replace(/[\n\r]/g,""));
			} else {
				res.end(r.replace(/\n/g, ""));
			}
		});
	});
};
