var client_mod = require("./client");
var appid = "game_line_www_xsjyl";
var df = 1000;
var num = 1;
if(process.argv.length >= 3){
	appid = process.argv[2];
	if(process.argv.length >=4){
		df = process.argv[3];
		if(df < 50){
			df = 50;
		}
	}
	if(process.argv.length >=5){
		num = Number( process.argv[4] );
	}
}

//112.124.0.222 115.29.165.213 115.29.162.108 112.124.44.47
//
var arr = ["test.vvku.com:8365"];
console.log(appid,arr);
setInterval(function(){
	if(num-- > 0){
		once();
	}
	
},100)


var num_pkt  = 0;
function Ping (){
	this.min_ping = 0;
	this.max_ping = 0;
	this.avg_ping = 0;
	this.total_ping = 0;
	this.num_ping = 0;
	this.ping_deploy_arr = [0,0,0,0,0,0];
	console.log("ping_deploy descript [ 0-10   11-50   51-100   101-150   151-200   200+ ]\r\n");
}
Ping.prototype.UpdatePing = function(ping){
	with(this){
		total_ping+=ping;
		num_ping+=1;
		avg_ping = Math.floor( total_ping/num_ping );
		if(min_ping == 0 || min_ping > ping){
			min_ping = ping;
		}
		if(max_ping == 0 || max_ping < ping){
			max_ping = ping;
		}
		if(ping < 10){
			ping_deploy_arr[0]++;
		}else if( ping < 50){
			ping_deploy_arr[1]++;
		}else if( ping < 100){
			ping_deploy_arr[2]++;
		}else if( ping < 150){
			ping_deploy_arr[3]++;
		}else if( ping < 200){
			ping_deploy_arr[4]++;
		}else{
			ping_deploy_arr[5]++;
		}
	}
}
var ping_class = new Ping();
var publish_client = null;
function once(){

	var cli = client_mod.Create(appid,arr);
	if(!publish_client)
		publish_client = cli;
	var id  = 0;
	cli.Connect();
	var timer = null;
	cli.on("open",function(){
		console.log("on open")
	})
	cli.on("close",function(err){
		clearInterval(timer);
		console.log("close err:",err);
	})
	cli.on("message",function(buf){
		if(!buf){
			console.log(buf);
		}
		var str = buf.toString();
		var obj = JSON.parse(str);
		var now = new Date().getTime();
		var  time = obj.time;
		var ping = now-time;
		ping_class.UpdatePing(ping);
		console.log(obj);
	})
	
	function Send(){
		var now = new Date().getTime();
		var pkt = {
			id:id++,
			time:now
		}
		cli.Send(JSON.stringify(pkt));
		num_pkt++;
	}

}
var publish_id = 0;
setInterval(function(){
	if(publish_client){
		var now = new Date().getTime();
		var pkt = {
			id:publish_id++,
			time:now
		}
		publish_client.Send(JSON.stringify(pkt));
		num_pkt++;
	}

},df)

setInterval(function(){
	console.log( 
	"send_num:",num_pkt,
	"min_ping:",ping_class.min_ping,
	"max_ping:",ping_class.max_ping,
	"avg_ping:",ping_class.avg_ping,
	"ping_deploy:",ping_class.ping_deploy_arr);
},10000)