var url = require("url");
var System = require("../../base/system");
var metaCtl=System.getObject("web.common.metaCtl");
var userCtl=System.getObject("web.auth.userCtl");
module.exports = function (app) {
	app.get("/auth",async function(req,res){
		await userCtl.authByCode(req);
		res.redirect("/");
	});
	app.get("/",async function(req,res){
		console.log(req.hostname);
		var appinfo=await metaCtl.getAppInfo(req);
		if(!appinfo){
			res.render("index",{appinfo:null,app:null});
		}else{
			res.render("index",appinfo);
		}
	
	});
	app.all("/web/*", function (req, res, next) {
		if (
			req.url.indexOf("checkLogin") > 0 ||
			req.url.indexOf("metaCtl") > 0 ||
			req.url.indexOf("getOssConfig") > 0) {
			return next();
		}
		if (!req.session.user) {
			var x = {
				status: -99,
				msg: "no login"
			};
			res.end(JSON.stringify(x));
		} else {
			//console.log(req.headers);
			next();
		}
	});
	app.get("/admin",async function(req,res){
		var appinfo=await metaCtl.getAppInfo(req);
		res.render("admin",appinfo);
	});
	app.get('/web/: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 params = [];
        params.push(methodName);
		params.push(req.body);
        params.push(req.query);
        params.push(req);
		var p = null;
		var invokeObj = System.getObject("web." + classPath);
		if (invokeObj["doexec"]) {
			p = invokeObj["doexec"].apply(invokeObj, params);
		}
		p.then(r => {
			res.end(JSON.stringify(r));
		});
	});
	app.post('/web/: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.body.clientIp = tClientIp;
		req.body.agent= req.headers["user-agent"];
		req.body.classname=classPath;
		params.push(methodName);
		params.push(req.body);
        params.push(req.query);
        params.push(req);
		var p = null;
		var invokeObj = System.getObject("web." + classPath);
		if (invokeObj["doexec"]) {
			p = invokeObj["doexec"].apply(invokeObj, params);
		}
		p.then(r => {
			res.end(JSON.stringify(r));
		});
	});
};
