var koa = require('koa');
var router = require('koa-router')();
var koaStatic = require('koa-static');
var serverlist = require('./serverlist.json');
var ajax = require('superagent');

var getServerInfo = function(serverinfo){
	if(serverinfo.querying){
		return;
	}
	serverinfo.querying = true;
	ajax.get(serverinfo.url + '/public/serverinfo').type('json').end(function(err, res){
		serverinfo.querying = false;
		if(err){
			serverinfo.status = err.toString();
		}else{
			if(res.body.code === 0){
				var info = res.body.data;
				serverinfo.status = info.status;
				serverinfo.total = info.total;
				serverinfo.online = info.online;
			}else{
				serverinfo.status = res.body.data.toString();
			}
		}
	});
}

var getAllServerInfo = function(){
	for(var i=0; i<serverlist.length; i++){
		getServerInfo(serverlist[i]);
	}
}

//定期刷新一下服务器列表状态
setInterval(function(){
	getAllServerInfo();
}, 5000);
getAllServerInfo();

// ajax.get('http://127.0.0.1:8000' + '/public/serverinfo')
// 	.type('json').end(function(err, res){
// 		console.log(err, res.body)
// 	});
//getServerInfo('http://127.0.0.1:8002').then(function(data){
//	console.log(data);
//}).catch(function(err){console.log('err', err.toString())});

function startGatewayServer() {
	if (!global['app']) {


		var app = global['app'] = koa();

		/*应用服务器异常*/
		app.on('error', function(err, ctx) {
			console.log('appError', err.stack);
		});

		/*系统异常处理*/
		process.on('uncaughtException', function(err) {
			console.log('uncaughtException', err.stack);
		});

		/*统计API调用的执行时间*/
		app.use(function*(next) {
			console.log('request:' + this.path);
			var start = Date.now();
			yield next;
			var ms = Date.now() - start;
			this.set('X-Response-Time', ms + 'ms');
		});

		app.use(koaStatic('./version'));
		//server
		router.all('/', function*(){
			this.body = "server is running";
		});
		//服务器列表
		router.all('/serverlist', function*(){
			this.body = {code:0, data:serverlist};
		});
		//热更新版本
		router.all('/version', function*(){
			this.body = {code:0, data:'1.0.1'};
		});
		//

		app.use(router.routes());

		var server = require('http').createServer(app.callback());

		/*绑定socket.io服务*/
		//require('./socket.io.js').bind(server);

		/*开始web服务器*/
		var port = 7000;
		server.listen(port, function() {
			console.log('server start at ' + port);
		});

	}
}

startGatewayServer();
