var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var PORT = 33333;
//var HOST = '127.0.0.1';
var dgram = require('dgram');
var SRPORT = -1;
var SRHOST = "";
function BuildMsg(protel,msg)
{
	return new Buffer("protel:" + protel + '#spe#msg:' + msg);
}

function SendMsg(message)
{
	if(SRPORT == -1)
	{
		return;
	}
	client.send(message, 0, message.length, SRPORT, SRHOST, function(err, bytes) {
    if (err) throw err;
    console.log('UDP message sent to ' + SRHOST +':'+ SRPORT);
});
}

/**
 * 私人聊天使用session
 */
var usersWS = {};

var client = dgram.createSocket('udp4');
client.bind(PORT);
client.on('message',function(message, remote){
	console.log('server ip:' + remote.address + ', port:' + remote.port +', message:' + message);
	if(message == "where is NodeJS?Tell wifinono!")
	{
		SRPORT = remote.port;
		SRHOST = remote.address;
		var msg = new Buffer("I'm here!");
		client.send(msg, 0, msg.length, remote.port, remote.address, function(err, bytes) {
				if (err) throw err;
				console.log('UDP message sent to ' + remote.address +':'+ remote.port);
			});
	}
	});

app.get('/', function(req, res){
	res.send('<h1>Welcome Realtime Server</h1>');
});

//在线用户
var onlineUsers = {};
//当前在线人数
var onlineCount = 0;
//聊天历史记录
var histroy = {};
//聊天记录数量
var hiscount = 0;
//需要记录的历史记录最大条数
var hisCountMax = 20;
io.on('connection', function(socket){
	var clientIp = socket.request.connection.remoteAddress;
	console.log('a user connected');
	var msg = "connection#spe#ip:" + clientIp;
	var msgbuf = BuildMsg("connection",msg);
	SendMsg(msgbuf);

	//监听新用户加入
	socket.on('login', function(obj){
		//将新加入用户的唯一标识当作socket的名称，后面退出的时候会用到
		socket.name = obj.userid;
		usersWS[socket.name] = socket;
		//检查在线列表，如果不在里面就加入
		if(!onlineUsers.hasOwnProperty(obj.userid)) {
			onlineUsers[obj.userid] = obj;
			//在线人数+1
			onlineCount++;
		}
		//向所有客户端广播用户加入
		io.emit('login', {onlineUsers:onlineUsers, onlineCount:onlineCount, user:obj});
		//向客户端发送历史记录
		socket.emit('histroy', {histroy:histroy, hiscount:hiscount, user:obj});
		console.log(obj.username+'加入了聊天室');
	});
	
	//监听用户退出
	socket.on('disconnect', function(){
		//将退出的用户从在线列表中删除
		if(onlineUsers.hasOwnProperty(socket.name)) {
			//退出用户的信息
			var obj = {userid:socket.name, username:onlineUsers[socket.name].username};
			
			//删除
			delete onlineUsers[socket.name];
			//在线人数-1
			onlineCount--;
			delete usersWS[socket.name];
			//向所有客户端广播用户退出
			io.emit('logout', {onlineUsers:onlineUsers, onlineCount:onlineCount, user:obj});
			console.log(obj.username+'退出了聊天室');
		}
	});
	//监听用户私聊内容
	socket.on('primessage',function(fromobj,toobj,fn){
		if(fromobj.userid != toobj.userid)
		{
			if(usersWS.hasOwnProperty(toobj.userid)) {
				var tosocket = usersWS[toobj.userid];
				tosocket.emit('primessage', fromobj);
				socket.emit('message',fromobj);
			}
		}
	});
	//监听用户发布聊天内容
	socket.on('message', function(obj){	
		var msg = "user:" + obj.username + "#spes#tm:" + obj.time + "#spes#content:" + obj.content + "#spes#ip:" + clientIp;
		var msgbuf = BuildMsg("message",msg);
		SendMsg(msgbuf);
		histroy[hiscount] = obj;
		if(hiscount >= hisCountMax)
		{
			for(var i = 0; i < hisCountMax; i++)
			{
				histroy[i] = histroy[i + 1];
			}
			//hiscount = 0;
		}
		else
		{
			hiscount++;
		}
		//向所有客户端广播发布的消息
		io.emit('message', obj);
		console.log(obj.username+'说：'+obj.content);
	});
  
});

http.listen(61616, function(err, bytes){
	if (err) throw err;
	console.log('listening on *:61616');
});