// https://gist.github.com/ismasan/299789
/*
The MIT License (MIT)
Copyright (c) 2014 Ismael Celis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-------------------------------*/
/*
Simplified WebSocket events dispatcher (no channels, no users)
var socket = new FancyWebSocket();
// bind to server events
socket.bind('some_event', function(data){
  alert(data.name + ' says: ' + data.message)
});
// broadcast events to all connected users
socket.send( 'some_event', {name: 'ismael', message : 'Hello world'} );
*/

var PfISWebSocket = function(session, task) {
	// location.protocol+
	var url = 'wss://'+location.hostname+(location.port ? ':'+location.port: '') + "/ws";

	if(typeof session !== 'undefined')
		url += "/" + session;

	if(typeof task !== 'undefined')
		url += "/" + task;

	console.log(url);

	var conn = new WebSocket(url);

	var callbacks = {};

	this.bind = function(event_name, callback) {
		callbacks[event_name] = callbacks[event_name] || [];
		callbacks[event_name].push(callback);
		return this;// chainable
	};

	this.send = function(event_name, event_data) {
		/*if(conn.readyState !== WebSocket.OPEN) {
			dispatch("close", null);
			return;
		}*/
		var payload = JSON.stringify({event:event_name, data: event_data});
		conn.send( payload ); // <= send JSON data to socket server
		return this;
	};

	// dispatch to the right handlers
	conn.onmessage = function(evt) {
		if(evt.data === "hb::") {
			console.log('got heartbeat');
			return;
		}
		var json = JSON.parse(evt.data);
		dispatch(json.event, json.data);
	};

	function show_errormessage(title, message, event) {
		var myerrordialog = $("#pfiswebsocket_errordialog");
		if(myerrordialog.length === 0) {
			console.log('must append errordialog');
			$("body").append("<div id='pfiswebsocket_errordialog' class='modal' tabindex='-1' role='dialog'><div class='modal-dialog'><div class='modal-content'><div class='modal-header'><h4 class='modal-title'></h4></div><div class='modal-body'></div><div class='modal-footer'></div></div><!-- /.modal-content --></div><!-- /.modal-dialog --></div><!-- /.modal -->");
			myerrordialog = $("#pfiswebsocket_errordialog");
		}

		myerrordialog.find(".modal-title").html(title);
		myerrordialog.find(".modal-body").html(message);
		myerrordialog.find('.modal-footer').html("<p class='small'>[code: " + event.code + "; Grund: '" + event.reason + "']</p>");

		$("#pfiswebsocket_errordialog").modal({ backdrop: 'static', keyboard: false });
		//$("#pfiswebsocket_errordialog").show();

		//$("body").append("<div style='position: absolute; top: 0; bottom: 0; left: 0; right: 0; background-color: lightgrey;'><table width='100%' height='100%'><tr valign='center' style='hight: 100%;'><td align='center'><b>"+message+"</b></td></tr></table></div>");
	}

	conn.onclose = function(e) {
		console.log('close:', e);

		if(e.code === 1001) { // going away
			console.log('WEBSOCKET: going away ...');
			setTimeout(function() {
				dispatch('close', {event: e});
			}, 1000); // we use a timeout here, so that when we simply go to another site, nothing happens!
			return;
		}

		if(e.code === 1011 && e.reason === "__no_session__found__") {
			var url = location.protocol+ '//'+location.hostname+(location.port ? ':'+location.port: '') + "/";
			console.log(url);
			show_errormessage("Die Sitzung ist nicht mehr gültig!", "Bitte <a href='"+url+"'>starten Sie eine neue</a>!", e);
			return;
		}

		dispatch('close', {event: e});
	};
	conn.onopen = function(){ dispatch('open',null)};
	conn.onerror = function(error) { console.log('error: ', error, error.type); };

	var dispatch = function(event_name, message) {
		var chain = callbacks[event_name];
		if(typeof chain == 'undefined') return; // no callbacks for this event
		for(var i = 0; i < chain.length; i++) {
			chain[i]( message );
		}
 	};

	this.bind_standard_close_handler = function() {
		this.bind("close", function(data) {
			console.log('CLOSED_HANDLER_CALLED');
			show_errormessage("Verbindung zu PfIS abgebrochen!", "<a href='javascript: location.reload(true);'>Bitte reload.</a><br>Sollte PfIS ausgefallen sein, versuchen Sie es bitte später noch einmal!", data.event);
		});
	};
};

generateUID = function() {
	return ("000000" + (Math.random()*Math.pow(36,6) << 0).toString(36)).slice(-6)
}
