var url = require("url");
var System = require("../../base/system");
module.exports = function (app) {
	app.get('/api/:gname/:qname/:method', function (req, res) {
		var classPath = req.params["qname"];
        var methodName = req.params["method"];
		var gname=req.params["gname"];
		
		classPath=gname+"."+classPath;
		var tClientIp = System.get_client_ip(req);
		req.clientIp = tClientIp;
		req.uagent= req.headers["user-agent"];
		req.classname=classPath;

		var params = [];
		params.push(gname);
        params.push(methodName);
		params.push(req.body);
        params.push(req.query);
        params.push(req);
		var p = null;
		var invokeObj = System.getObject("api." + classPath);
		if (invokeObj["doexec"]) {
			p = invokeObj["doexec"].apply(invokeObj, params);
		}
		p.then(r => {
			res.end(JSON.stringify(r));
		});
	});
	app.post('/api/:gname/:qname/:method', function (req, res) {
		var classPath = req.params["qname"];
        var methodName = req.params["method"];
        var gname=req.params["gname"];
        var params = [];
        classPath=gname+"."+classPath;
		var tClientIp = System.get_client_ip(req);

		req.clientIp = tClientIp;
		req.uagent= req.headers["user-agent"];
		req.classname=classPath;

		params.push(gname);
		params.push(methodName);
		params.push(req.body);
        params.push(req.query);
        params.push(req);
		var p = null;
		var invokeObj = System.getObject("api." + classPath);
		if (invokeObj["doexec"]) {
			p = invokeObj["doexec"].apply(invokeObj, params);
		}
		p.then(r => {
			var rs=JSON.stringify(r)
			.replace(/%5C/g,'%5C%5C')
                      .replace(/%22/g,"%5C%22")
                      .replace(/%2F/g,'%5C%2F')
                      .replace(/%08/g,'%5Cb')
                      .replace(/%0C/g,'%5Cf')
                      .replace(/%0A/g,'%5Cn')
                      .replace(/%0D/g,'%5Cr')
                      .replace(/%09/g,'%5Ct');
			res.end(rs);
		});
	});
};
