var socket;
var time;
var userId = "";

function openClick(formUserId) {
	userId = formUserId;
	connection(userId);
}

function closeClick() {
	if (socket) {
		socket.close();
	}
}


function connection(fromUserId) {
	console.log("connection()");
	var url = window.config.webSocketUrl + fromUserId;
	console.log(url);
	//判断当前浏览器是否支持WebSocket
	if (window.WebSocket) {
		socket = new WebSocket(url);
	} else {
		alert('当前浏览器不支持webSocket')
	}
	//连接发生错误的回调方法
	socket.onerror = function() {
		console.log("error...");
		reconnection();
	};
	//连接成功建立的回调方法
	socket.onopen = function() {
		console.log("onopen()");
		//heartCheck.reset().start();   // 成功建立连接后，重置心跳检测
	}
	//接收到消息的回调方法
	socket.onmessage = function(event) {
		console.log("onmessage>>>>>>" + event.data);
		//heartCheck.reset().start();    // 如果获取到消息，说明连接是正常的，重置心跳检测
		if (event.data === "") return;
		var data = JSON.parse(event.data);
		window.receiveMsg(data);
	}
	//连接关闭的回调方法
	socket.onclose = function() {
		console.log("onclose()");
		reconnection();
	}
}

//重连
function reconnection() {
	//与服务器连接成功
	if (socket && socket.readyState == 1) {
		clearTimeout(time);
	} else {
		//已经关闭链接，则重新连接
		if (socket && socket.readyState == 3) {
			connection(userId);
		}
		//0正在服务器建立连接,2正在关闭与服务器的连接
		time = setTimeout(function() {
			reconnection();
		}, 1000);
	}
}


module.exports = {
	openClick: openClick,
	closeClick: closeClick,
	connection: connection,
	reconnection: reconnection
}
