var msgDb = require('./msgDb');

var clients = {};
var ids = [];

function addNewClient (client) {
	console.log("up user:" + client.id);
	if(!clients[client.id]) {
		clients[client.id] = [];
	}
	clients[client.id].push(client);
	if(ids.indexOf(client.id) == -1) {
		ids.push(client.id);	
	}
};

function removeClient(socket) {
	console.log("remove " + socket.id);

	var tmp_clients = clients[socket.uname];
	if (tmp_clients && tmp_clients instanceof Array) {
		for(var index = 0; index < tmp_clients.length ; index ++) {
			if (tmp_clients[index] && tmp_clients[index].socket == socket) {
				console.log("down" + tmp_clients[index].uname);
				delete tmp_clients[index];
				break;
			}
		}
		if(tmp_clients.length == 0) {
			ids.splice(ids.indexOf(socket.uname), 1);
		}
	}

};

function sendEventMsgToId(toId,event) {
	if(ids.indexOf(toId) > -1) {
		console.log(event);
		clients[toId].forEach(function(client){
			client.socket.emit("message",event);
			console.log(client.socket.id + ' send message');
		});
	}else {
		console.log("ids:" + ids);
		console.log("no such id:" + toId);
	}
}


module.exports.newConnection = function(socket) {
	socket.on('disconnect',function(){
		removeClient(socket);
	});

	socket.on('login',function(msg) {
		console.log("socket:" + socket.id + "  msg:" + msg);
		msg = JSON.parse(msg); 
		if(msg.uname && msg.pword) {
			var client = {};
			var uid = msg.uname;
			client.id = uid;
			socket.uname = uid;
			client.socket = socket;
			addNewClient(client);
			msgDb.workForToId(uid,function(msgs){
				msgs.forEach(function(tmpMsg){
					sendEventMsgToId(uid , tmpMsg);
				});	
			});
		}else {
			console.log("error");
		}
	});
	
	socket.on('answer',function(msg){
		msgDb.answerMsg(msg);
	});
};

module.exports.sendMsgToId = function (fromId,toId,msg){
	var timestamp = (new Date()).valueOf(); 
	var event = {};
	event['fromId'] = fromId;
	event['toId'] = toId;
	event['msg'] = msg;
	event['time'] = timestamp;
	if(clients[toId]) {
		msgDb.addMsg(event,function(msg){
			sendEventMsgToId(toId,msg);
		});
	}
};

module.exports.clients = clients;
module.exports.ids = ids;

