'use strict';

// Declare app level module which depends on views, and components
angular.module('screenshareApp', [
]).factory('cometd', function(){
	return $.cometd;
}).controller('ClientCtrl', function($scope, $http, cometd) {
	$scope.accessCode = "";
	$scope.connected = false;
	
	$scope.startClient = function(){
		$scope.feedback = "";
		var shareMatchConfig = {headers: {'GMS-User': 'gms_comet_user_' + $scope.accessCode}};
		$http.get("../1/service/share-match?_access_code=" + $scope.accessCode, shareMatchConfig).then(function(response){
			let data = response.data;
			console.log(data);
			$scope.serviceId = data._id;
			var cometdConfig = {url: "../cometd",
					requestHeaders: {'GMS-User': 'gms_comet_user_' + $scope.accessCode}};
			cometd.unregisterTransport('websocket');
			cometd.configure(cometdConfig);
			cometd.handshake(function(reply){
				if (reply.successful){
					cometd.subscribe('/_genesys', function(message){
						var prefix = "gsg-storage-update-";
						if (!message.data.tag || !message.data.tag.substring(0, prefix.length) === prefix){
							return;
						}
						var guid = message.data.tag.substring(prefix.length);
						$scope.imageSource = "../1/storage/binary/" + guid + "/screen?" + (Math.random() * 100000000000000000);
						$scope.$apply();
					});
					cometd.addListener('/meta/connect', function(message){
						$scope.connected = message.successful;
					})
				} else {
					$scope.feedback = "Connect failed."
				}
			});
		});
	}
	
	$scope.stopClient = function(){
		cometd.disconnect(function(reply) {
			$scope.connected = !reply.successful;
			$scope.$apply();
		});
		$scope.connected = false;
	}
});
