/******************************************************************************
@owner: SVSi
@author: Arthur Johnson
@functions: WebSocket js class
@webSocket
*******************************************************************************/
var Server = {name: location.host, ip: location.host, 
	errors: true, warnings: true, notices: true,
	outbound: true, inbound: false, debugging: false};
var Client = {username: false};
var binsocket = false;

function startWebsocket(onComplete, onError){
	servername = location.host;
	if (!servername || servername == '') servername = 'localhost';
	var address = 'http://'+servername+':3001';
	window.websocket = io.connect(address, {secure: false});
	websocket.getMessage = noop; websocket.getCustom = noop;
	websocket.on('connect_failed', function(){
		console.log('<--websocket error-->');
		if (onError) onError();
	});
	websocket.on('connect', function(){
		console.log('<--websocket connect-->');
		if (onComplete) onComplete();
	});	
	websocket.on('message', function(opts){
		try {
			if (window.__verbose) console.log('err on message?', opts.command);
			if (Server.inbound) console.log('Incoming from Server: ', opts);
			if (Server.debugging) console.log('Server_Debugging: '+json_encode(opts));
			if (!opts || !opts.command) return;
			switch (opts.command){
				case 'jslog': if (window._console) _console.log.apply(console, opts.args); break;
				case 'jserror': if (window._console) _console.error.apply(console, opts.args); break;
				case 'security': if (dataproject.core.passkey) $('#security').show(); break;
				case 'homepage': if (opts.url) window.location = opts.url; break;
				case 'message': websocket.getMessage(opts); break;
				case 'download': window.location = opts.filename; break;
				case 'import_buttons': pb.importButtonLibrary(opts.data); break;
				case 'import_templates': pb.importTemplateLibrary(opts.data); break;
				case 'project_imported': try {
					pb.user.templates = []; pb.user.buttons = [];
					$('#templatesGrid').html(''); $(document.getElementById('User Buttons')).html('');
					pb.loadProject({puid: opts.puid, fromDB: false, name: opts.name});
				} catch (e){console.log('project import error');}; break;
				case 'error':
					pb.openDialog({
						content: '<br><center>An unexpected error has occured.</center>',
						confirm: 'ok', cancel: false, style: {height: '120px'},
						onConfirm: function(){pb.closeDialog();}
					});
					break;
				case 'image': case 'module':
					console.log('got img back', opts);
					if (opts.puid){
						try {pb.project.core.puid = opts.puid;}
						catch (e){try {wizardproject.puid = opts.puid} catch (e){}}
					}
					for (var i=window.callbacks.length; i--;){
						if (opts.callback_id == window.callbacks[i].callback_id){
							window.callbacks[i].callback(opts);
							removeFromArray(window.callbacks, window.callbacks[i]);
						}
					}
					break;
				case 'set_id':
					websocket.id = opts.websocket_id;
					var loc = location.host ? location.host : 'localhost';
					binsocket = new BinaryClient('ws://' + loc + ':3001/binaryjs');
					console.log('binsocket...');
					binsocket.on('stream', function(stream, opts){
						console.log('stream', opts);
						switch (opts.command){
							case 'download':
								var parts = [];
								stream.on('data', function(data){parts.push(data);});
								stream.on('end', function(){saveAs(new Blob(parts), opts.name);});
								break;
							default:
								break;
						}
					});
					binsocket.on('open', function(){
						console.log('<--binarysocket connect-->');
						binsocket.send(false, {command: 'id', _id: opts.websocket_id});
					});
					binsocket.on('error', function(err){
						console.log('binsocket error:', err);
					});
					break;
				case 'return_data':
					if (Server.errors && !undef(opts.error)) console.log('Server Error: ', opts.error);
					if (Server.warnings && !undef(opts.warning)) console.log('Server Warning: ', opts.warning);
					if (Server.notices && !undef(opts.notice)) console.log('Server Notice: ', opts.notice);
					if (Sandbox.sockets) for (var i=0; i<Sandbox.sockets.length; i++){
						if (Sandbox.sockets[i].sock_id == opts.sock_id){
							if (!undef(opts.data) && Sandbox.sockets[i].onMessage) Sandbox.sockets[i].onMessage(opts.data);
							if (opts.close){
								if (Sandbox.sockets[i].onDestroy) Sandbox.sockets[i].onDestroy();
								removeFromArray(Sandbox.sockets, Sandbox.sockets[i]);
							}
							return;
						}
					}
					break;
				case 'unitlist':
					var str = opts.data;
					var obj = {};
					while (str.indexOf('\r') != -1){
						var key = str.substring(0, str.indexOf(':'));
						var key2 = str.substring(0, str.indexOf(':')).toLowerCase();
						var valueString = str.substring(str.indexOf(':')+1, str.indexOf('\r'));
						obj[key] = valueString;
						obj[key2] = valueString;
						if (key.indexOf('SVSI_A') !== -1){
							obj.generaltype = 'TXRX'; obj.type = 'ATR';
						}
						else if (key.indexOf('SVSI_VO') !== -1){
							obj.generaltype = 'VOD'; obj.type = 'VOD';
						}
						else if (key.indexOf('SVSI_VW') !== -1){
							obj.generaltype = 'TXRX'; obj.type = 'WP';
						}
						else if (key.indexOf('SVSI_R') !== -1){
							obj.generaltype = 'RX'; obj.type = 'RX';
						}
						else if (key.indexOf('SVSI_T') !== -1){
							obj.generaltype = 'TX'; obj.type = 'TX';
						}
						else if (key.indexOf('SVSI_C') !== -1){
							obj.generaltype = 'COM'; obj.type = 'COM';
						}
						else if (key.indexOf('SVSI_W') !== -1){
							obj.generaltype = 'WPC'; obj.type = 'WPC';
						}
						else if (key.indexOf('SVSI_D') !== -1){
							obj.generaltype = 'TXRX'; obj.type = 'DVR';
						}
						str = str.substring(str.indexOf('\r')+1);
					}
					if (obj.nickname) obj.name = obj.nickname;
					if (obj.ipaddr) obj.ip = obj.ipaddr;
					if (obj.name && obj.ip) unitlist.push(obj); console.log('comparing', ngmodel.unitlist, unitlist);
					if (!ngmodel.unitlist) ngmodel.unitlist = [];//unitlist;
					//else {
						for (var i=0; i<unitlist.length; i++){
							var found = false;
							for (var j=0; j<ngmodel.unitlist.length; j++){
								if (ngmodel.unitlist[j].ip === unitlist[i].ip) found = true;
							}
							if (!found) ngmodel.unitlist.push(unitlist[i]);
						}
					//}
					break;
				default:
					websocket.getCustom(opts);
					break;
			}
		} catch(e){
			if (window.__verbose) console.log('websocket msg error', opts);
		}
	});
	websocket.on('disconnect', function(){
		console.log('<--websocket disconnect-->');
	});
	return websocket;
}