var lbsModule = angular.module('lbs', ['ngRoute', 'lbsControllers']);

lbsModule.config([
	'$routeProvider',
	function($routeProvider) {
		$routeProvider
			.when('/summary',                    { templateUrl: 'html/summary.html',       controller: 'lbsSummaryCtrl' })
			.when('/topics',                     { templateUrl: 'html/topics.html',        controller: 'lbsTopicsCtrl' })
			.when('/subscriptions',              { templateUrl: 'html/subscriptions.html', controller: 'lbsSubscriptionsCtrl' })
			.when('/events/:condition',          { templateUrl: 'html/filterEvents.html',  controller: 'lbsFilterEventsCtrl' })
			.when('/events/:page/:size/:topic*', { templateUrl: 'html/eventsByTopic.html', controller: 'lbsEventsByTopicCtrl' })
			.otherwise({ redirectTo: '/summary' });
	}
]);

lbsModule.controller('moduleMenuCtrl', function ($scope, $http, $location) {

	$scope.tools = [];
	
	$http.get('ajax/externalTools').then(function(res) {
		$scope.tools = res.data;
	}, function(res) {
		alert("error");
	});
		
	$scope.isActive = function(regex) {
		var re = new RegExp(regex);
		return re.test($location.path());
	}
});

lbsModule.directive('twoStepButton', function($timeout) {
	return {
		restrict: 'E',
		scope: {
			'label'        : '@',
			'action'       : '&'
		},
		templateUrl: 'html/twoStepButton.template.html',
		link: function(scope, iElement, iAttrs, ctrl) {
			scope.status = 0;
			
			scope.doAction = function() {
				if (scope.promise) {
					$timeout.cancel(scope.promise);
				}
				if (scope.status == 0) {
					scope.status = 1;
					scope.promise = $timeout(function() { scope.status = 0 }, 4000);
				} else {
					scope.status = 0;
					scope.action();
				}
			}
		}
	}
});

lbsModule.directive('adminOperation', function($timeout) {
	return {
		restrict: 'A',
		replace: true,
		scope: {
			'label'        : '@',
			'description'  : '@',
			'alert'        : '@',
			'action'       : '&'
		},
		templateUrl: 'html/adminOperation.template.html',
		link: function(scope, iElement, iAttrs, ctrl) {
			scope.status = 0;
			
			scope.doAction = function() {
				if (scope.promise) {
					$timeout.cancel(scope.promise);
				}
				if (scope.status == 0) {
					scope.status = 1;
					scope.promise = $timeout(function() { scope.status = 0 }, 4000);
				} else {
					scope.status = 0;
					$('.modal').modal('hide');
					scope.action();
				}
			}
		}
	}
});



//---------------------------------------------------------------------------------------------------------------------//

var lbsControllers = angular.module('lbsControllers', []);

lbsControllers.controller('lbsSummaryCtrl', function ($scope, $http, $sce, $location, $routeParams) {
	$scope.summary = {};
	
	$scope.refresh = function() {
		$http.get('ajax/summary').then(function(res) {
			$scope.summary = res.data;
		}, function() {
			alert("error");
		});
	};
	
	$scope.resetCounters = function() {
		$http.get('ajax/resetCounters').then(function(res) {
			$scope.summary = res.data;
		}, function() {
			alert("error");
		});
	};
	
	$scope.refresh();
});

//---------------------------------------------------------------------------------------------------------------------//

lbsControllers.controller('lbsSubscriptionsCtrl', function ($scope, $http, $sce, $location, $routeParams) {
	$scope.list = [];
	$scope.availableTopics = [];
	$scope.subscriber = '';
	$scope.topic = '';
	$scope.frequency = '';
	$scope.topicType = '';
	$scope.topicParts = [];
	$scope.topicConditions = [];
	$scope.topicRegex = '';
	
	$http.get('api/topic-types').then(function(res) {
		$scope.availableTopics = res.data;
	}, function() {
		alert("error");
	});
	
	$scope.refresh = function() {
		$http.get('api/subscriptions').then(function(res) {
			$scope.list = res.data;
		}, function(res) {
			alert("error");
		});
	};
	
	$scope.resetFormFields = function() {
		$scope.subscriber = '';
		$scope.topic = '';
		$scope.frequency = '';
		$scope.topicType = '';
		$scope.topicParts = [];
		$scope.topicConditions = [];
		$scope.topiceRegex = '';
	}
	
	$scope.onSelectTopicType = function(topicType) {
		$scope.topicParts = [];
		$scope.topicRegex = topicType.regex;

		angular.forEach(topicType.expression.split('/'), function(val) {
			if (val.length > 2 && val.charAt(0) == '<' && val.charAt(val.length - 1) == '>') {
				$scope.topicParts.push({ 'name' : val, variable : true, 'value' : '' });
			} else {
				$scope.topicParts.push({ 'name' : val, variable : false, 'value' : val });
			}
		});
		
		$scope.updateTopic();
	}
	
	$scope.updateTopic = function() {
		t = '';
		for (var i=0; i < $scope.topicParts.length; i++) {
			if ($scope.topicParts[i].value) {
				if (i == 0) { 
					t += $scope.topicParts[i].value
				} else {
					t += '/' + $scope.topicParts[i].value;
				}
			} else {
				$scope.topic = '';
				return;
			}
		}
		$scope.topic = t;
	}
	
	$scope.addCondition = function() {
		$scope.topicConditions.push({
			'field'      : '', 
			'fieldType'  : '',
			'operator'   : '',
			'listParams' : [ { 'value' : '', 'otherValue': '' } ]
		});
	}

	$scope.removeCondition = function(idx) {
		$scope.topicConditions.splice(idx, 1);
	}
	
	$scope.add = function(subscriber, topic, frequency, mode, conditions) {
		
		$http.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";
		$http.post('api/subscriptions', {
			'subscriber' : subscriber,
			'topic'      : topic,
			'frequency'  : frequency,
			'mode'       : mode,
			'conditions' : conditions
		}).then(function(res) {
			$scope.list.push(res.data);
		}, function(res) {
			alert("error");
		});
	};
	
	$scope.startMatching = function(id) {
		$http.get('api/matching/start/' + id).then(function(res) {
			alert("Matching in queue");
		}, function(res) {
			alert("Error: The functionality could be disabled in current configuration profile !");
		});
	};
		
	$scope.resetNotificationDate = function(id) {
		if (confirm("Are you sure ?")) {
			$http.delete('api/subscriptions/' + id + '/date').then(function(res) {
				$scope.refresh();
			}, function(res) {
				alert("error");
			});
		}
	};
		
	$scope.remove = function(id) {
		if (confirm("Are you sure ?")) {
			$http.delete('api/subscriptions/' + id).then(function(res) {
				$scope.refresh();
			}, function(res) {
				alert("error");
			});
		}
	};
	
	$scope.refresh();
});

//---------------------------------------------------------------------------------------------------------------------//

lbsControllers.controller('lbsTopicsCtrl', function ($scope, $http, $sce, $location, $routeParams) {
	$scope.list = [];
	$scope.segments = [];
	
	$scope.refresh = function() {
		$http.get('api/topic-types').then(function(res) {
			$scope.list = res.data;
		}, function(res) {
			alert("error");
		});
	};
	
	$scope.resetFormFields = function() {
		$scope.segments = [{},{}];
		$scope.topicName = '';
		$scope.topicProducerId = '';
		$scope.topicExpression = '';
		$scope.topicMapKeys = [];
	}
	
	$scope.updateTopicExpression = function() {
		var s = ""
		
		for (var i=0; i<$scope.segments.length; i++) {
			if ($scope.segments[i].type && $scope.segments[i].value) {
				if (i > 0) { s += '/'; }
				
				if ($scope.segments[i].type == 'Fixed') {
					s += $scope.segments[i].value;
				} else {
					s += '<' + $scope.segments[i].value + '>';
				}
			} else {
				$scope.topicExpression = '';
				return;
			}
		}	
		
		$scope.topicExpression = s;		
	}	
	
	$scope.add = function(name, producerId, expression, mapKeys) {
		$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
		$http.post('api/topic-types/add', $.param({
			'name'        : name,
			'expression'  : expression,
			'producerId'  : producerId,
			'mapKeys'     : mapKeys.join()
		})).then(function(res) {
			$scope.list.push(res.data);
		}, function(res) {
			alert("error");
		});
	};
	
	$scope.refresh();
});

//---------------------------------------------------------------------------------------------------------------------//

lbsControllers.controller('lbsFilterEventsCtrl', function ($scope, $http, $sce, $location, $routeParams) {
	$scope.list = [];
	
	$scope.cond = $routeParams.condition;
	
	$scope.onlyWithSubscriptions = ($scope.cond != 'all');
	
	$scope.reloadWithCondition = function() {
		$location.url($scope.onlyWithSubscriptions ? '/events/withSubscriptions' : '/events/all');
	}
	
	$scope.refresh = function() {
		var url = $scope.onlyWithSubscriptions ? "api/events/topics/withSubscriptions" : "api/events/topics/all";
		
		$http.get(url).then(function(res) {
			$scope.list = res.data;
		}, function(res) {
			alert("error");
		});
	};
	
	$scope.refresh();
});

//---------------------------------------------------------------------------------------------------------------------//

lbsControllers.controller('lbsEventsByTopicCtrl', function ($scope, $http, $sce, $location, $routeParams) {
	$scope.list = [];
	$scope.page     = $routeParams.page;
	$scope.pageSize = $routeParams.size;
	$scope.topic    = $routeParams.topic;

	$scope.refresh = function() {
		$http.get('api/events/byTopic/' + $scope.page + '/' + $scope.pageSize + '?topic=' + $scope.topic).then(function(res) {
			$scope.list = res.data;
		}, function(res) {
			alert("error");
		});
	};
	
	$scope.refresh();
});
               
