var webSocket;
var webSocketConfig;

var webSocket_PRESENTER = "presenter";
var webSocket_MEMBER = "member";

function initWebSocket(config) {
	webSocketConfig = $.extend({
		mode: null,
		identifier: null,
		user: null,
		onopen: function () { },
		connection: function () { },
		onmessage: function (message) { },
		onclose: function () { }
	}, config);

	if (webSocketConfig.mode != webSocket_PRESENTER && webSocketConfig.mode != webSocket_MEMBER) {
		alert("Error: empty mode");
		return false;
	}

	if (webSocketConfig.identifier.length == 0) {
		alert("Error: empty identifier");
		return false;
	}

	if (webSocketConfig.mode == webSocket_MEMBER && webSocketConfig.user.length == 0) {
		alert("Error: empty user");
		return false;
	}

	try {
		webSocket = new WebSocket("ws://46.242.130.97:9000/" + webSocketConfig.mode + "/" + webSocketConfig.user + "/" + webSocketConfig.identifier);
		webSocket.onopen = function (msg) {
			logWebSocket("WebSocket:onopen");

			webSocketConfig.onopen();
		};
		
		webSocket.connection = function (ws) {
			logWebSocket("WebSocket:connection");

			webSocketConfig.connection();
		};

		webSocket.onmessage = function (message) {
			logWebSocket("WebSocket:onmessage");

			messageWebSocket(message);
		};

		webSocket.onclose = function (msg) {
			logWebSocket("WebSocket:onclose");

			webSocketConfig.onclose();

			logWebSocket("Disconnected - status " + this.readyState);
		};
	} catch (exception) {
		logWebSocket(exception);
	}
}

function logWebSocket(message) {
	console.log(message);
}

function sendWebSocket(message, user) {
	if (typeof message === "object") {
		message = JSON.stringify(message).toString();
	}

	if (!message || message.length == 0) {
		return false;
	}

	if (typeof user === "undefined") {
		user = "";
	}

	var sendMessage = JSON.stringify({
		mode: webSocketConfig.mode,
		identifier: webSocketConfig.identifier,
		user: user,
		message: message
	}).toString();

	try {
		webSocket.send(sendMessage);
	} catch (exception) {
		logWebSocket(exception);
	}
}

function sendNoJSONWebSocket(messqge) {
	try {
		webSocket.send(messqge);
	} catch (exception) {
		logWebSocket(exception);
	}
}

function messageWebSocket(message) {
	try {
		parseMessageWebSocket(message.data);
	} catch (error) {
		
	}
}

function parseMessageWebSocket(message) {
	var messageJSON = JSON.parse(message);

	if (webSocketConfig.identifier != messageJSON.identifier) {
		return false;
	}

	if (webSocketConfig.mode == webSocket_PRESENTER && messageJSON.mode == webSocket_MEMBER) {
		
	} else if (webSocketConfig.mode == webSocket_MEMBER && messageJSON.mode == webSocket_PRESENTER) {

	} else {
		return false;
	}

	/*if (message.user.length > 0 && webSocketConfig.user != message.user) {
		return false;
	}*/

	webSocketConfig.onmessage(messageJSON.message);
}