var openaireBroker = angular.module('openaireBroker', ['ngRoute', 'angular.backtop', 'openaireBrokerControllers', 'rzModule', 'LocalStorageModule', 'base64']);

openaireBroker.config([
	'$routeProvider',
	function($routeProvider) {
		$routeProvider
			.when('/login',                { templateUrl: 'login.html',         controller: 'loginCtrl' })
			.when('/datasources',          { templateUrl: 'datasources.html',   controller: 'datasourcesCtrl' })
			.when('/q/:page/:encodedJson', { templateUrl: 'query.html',         controller: 'queryCtrl' })
			.when('/subscriptions',        { templateUrl: 'subscriptions.html', controller: 'subscriptionsCtrl' })
			.when('/ntf/:page/:subscrId',  { templateUrl: 'notifications.html', controller: 'notificationsCtrl' })
			.otherwise({ redirectTo: '/login' });
	}
]);

openaireBroker.factory('loginService', function(localStorageService) {
	var user;
	var tmpPath;
	
	var setUser = function(aUser) { 
		user = aUser;
		if (user) {
			localStorageService.set('openaire_broker_user', user);
		} else {
			localStorageService.clearAll();
		}
	};

	var getUser = function() {
		if (!user) {
			 user = localStorageService.get('openaire_broker_user');
		}
		return user;
	};
	
	return {
		setUser    : setUser,
		getUser    : getUser,
		isLogged   : function()  { return getUser() ? true : false },
		getTmpPath : function()  { return tmpPath },
		setTmpPath : function(p) { tmpPath = p },
	}
});

openaireBroker.run(function ($rootScope, $location, loginService) {
	$rootScope.$on('$routeChangeStart', function (event) {
		if (!loginService.isLogged()) {
			if ($location.path() != '/login') {
				loginService.setTmpPath($location.path());
			}
			$location.path('/login');
		} else {
			loginService.setTmpPath('');
		}
	});
});

openaireBroker.controller('moduleMenuCtrl', function ($scope, $http, $location, loginService) {
	$scope.isActive = function(regex) {
		var re = new RegExp(regex);
		return re.test($location.path());
	}
	
	$scope.$watch(loginService.isLogged, function (value, oldValue) {
		if(!value && oldValue) {
			$location.path('/login');
	    }
	}, true);
	
	$scope.getUser = function() {
		return loginService.getUser()
	}

	$scope.isLogged = function() {
		return loginService.isLogged();
	}
	
	$scope.logout = function() {
		return loginService.setUser('');
	}

});

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

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


openaireBrokerControllers.controller('loginCtrl', function ($scope, $location, loginService) {
	
	$scope.isLogged = function() {
		return loginService.isLogged();
	}
	
	$scope.performLogin = function(email) {
		loginService.setUser(email);
		$location.path(loginService.getTmpPath() ? loginService.getTmpPath() : "/datasources");
	}
});

openaireBrokerControllers.controller('datasourcesCtrl', function ($scope, $http, $sce, $location, $routeParams, $timeout, $base64, loginService) {
	$scope.datasources = [];
	$scope.topics = [];
	$scope.dsName = "";

	$scope.refresh = function() {
		$scope.datasources = [];
		$http.get('../api/openaireBroker/datasources').then(function(res) {
			$scope.datasources = res.data;
		}, function(res) {
			alert("error");
		});
	};
	
	$scope.browseTopics  = function(dsName) {
		$scope.topics = [];
		$scope.dsName = dsName;
		
		$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
		$http.get('../api/openaireBroker/topicsForDatasource?ds=' + encodeURIComponent(dsName)).then(function(res) {
			$scope.topics = res.data;
		}, function(res) {
			alert("error");
		});
	}
	
	$scope.gotoEventsPage = function(ds, topic) {
		var query = {
			'datasource' : ds,
			'topic'      : topic,
			'trust'      : {'min': 0, 'max': 1},
			'titles'     : [],
			'authors'    : [],
			'subjects'   : [],
			'dates'      : []
		};
		var path = '/q/0/' + encodeURIComponent($base64.encode(angular.toJson(query)))

		$timeout(function() { $location.path(path); }, 500);
	}
	
	$scope.calculateTotal = function(list) {
		var total = 0;
		angular.forEach(list, function(i) {
			total += i.size;
		});
		return total;
	}
	
	$scope.refresh();
});


openaireBrokerControllers.controller('queryCtrl', function ($scope, $http, $sce, $location, $routeParams, $timeout, $base64, loginService) {
	$scope.eventsPage = null;
	$scope.page = $routeParams.page;
	$scope.encodedQuery = $routeParams.encodedJson;
	$scope.query = angular.fromJson($base64.decode(decodeURIComponent($scope.encodedQuery)));
	
	$scope.refresh = function() {
		$http.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";
		$http.post('../api/openaireBroker/events/' + $scope.page + '/20', $scope.query).then(function(res) {
			$scope.eventsPage = res.data;
		}, function(res) {
			alert("error");
		});
	}
	
	$scope.gotoPage = function(page) {		
		$location.path('/q/' + page + '/' + $scope.encodedQuery);
	} 
	
	$scope.gotoEventsPageAdv = function(q) {
		var query = {
			'datasource' : q.datasource,
			'topic'      : q.topic,
			'trust'      : q.trust,
			'titles'     : q.titles.filter($scope.isValidString),
			'authors'    : q.authors.filter($scope.isValidString),
			'subjects'   : q.subjects.filter($scope.isValidString),
			'dates'      : q.dates.filter($scope.isValidRange)
		};

		var path = '/q/0/' + encodeURIComponent($base64.encode(angular.toJson(query)))

		$timeout(function() { $location.path(path); }, 500);
	}
	
	$scope.isValidString = function(s) {
		return (s && s.trim().length > 0);  
	}
	$scope.isValidRange = function(s) {
		return (s && ((s.min && s.min.trim().length > 0) || (s.max && s.max.trim().length > 0)));  
	}
	
	$scope.isAuthorHighlighted = function(author, list) {
		if (list) {
			for (var i=0; i<list.length; i++) {
				if (author.fullname + author.orcid  == list[i].fullname + list[i].orcid) {
					return true;
				}
			}
		}
		return false;
	}
	
	$scope.isSubjectHighlighted = function(subject, list) {
		if (list) {
			for (var i=0; i<list.length; i++) {
				if (subject.value == list[i].value) {
					return true;
				}
			}
		}
		return false;
	}
	
	$scope.isInstanceHighlighted = function(instance, list) {
		if (list) {
			for (var i=0; i<list.length; i++) {
				if (instance.url == list[i].url && instance.license == list[i].license && instance.hostedby == list[i].hostedby) {
					return true;
				}
			}
		}
		return false;
	}
	
	$scope.isProjectHighlighted= function(project, list) {
		if (list) {
			for (var i=0; i<list.length; i++) {
				if (project.openaireId == list[i].openaireId) {
					return true;
				}
			}
		}
		return false;
	}
	
	$scope.isPidHighlighted = function(pid, list) {
		if (list) {
			for (var i=0; i<list.length; i++) {
				if (pid.value == list[i].value && pid.type == list[i].type) {
					return true;
				}
			}
		}
		return false;
	}
	
	$scope.isDatasetHighlighted= function(dataset, list) {
		if (list) {
			for (var i=0; i<list.length; i++) {
				if (dataset.openaireId == list[i].openaireId) {
					return true;
				}
			}
		}
		return false;
	}

	$scope.isSoftwareHighlighted= function(sw, list) {
		if (list) {
			for (var i=0; i<list.length; i++) {
				if (sw.openaireId == list[i].openaireId) {
					return true;
				}
			}
		}
		return false;
	}

	
	$scope.isRelatedPublicationHighlighted= function(pub, list) {
		if (list) {
			for (var i=0; i<list.length; i++) {
				if (pub.openaireId == list[i].openaireId) {
					return true;
				}
			}
		}
		return false;
	}
	
	$scope.prepareAdvancedSearchForm = function() {
		$scope.tempQuery = angular.copy($scope.query);
		if ($scope.tempQuery.titles.length   == 0) { $scope.tempQuery.titles.push(''); }
		if ($scope.tempQuery.authors.length  == 0) { $scope.tempQuery.authors.push(''); }
		if ($scope.tempQuery.subjects.length == 0) { $scope.tempQuery.subjects.push(''); }
		if ($scope.tempQuery.dates.length    == 0) { $scope.tempQuery.dates.push({'min':'','max':''}); }
		
		$timeout(function() {
			$scope.$broadcast('rzSliderForceRender'); //Force refresh sliders on render. Otherwise bullets are aligned at left side.
		}, 1000);
	}
	
	$scope.prepareSubscriptionForm = function() {
		$scope.subscription = {
			'subscriber' : loginService.getUser(),
			'frequency'  : '',
			'mode'       : '',
			'query'      : $scope.query
		};
	}
	
	$scope.createSubscription = function() {
		$http.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";
		$http.post('../api/openaireBroker/subscribe', $scope.subscription).then(function(res) {
			alert("New registered subscription, ID: " + res.data.subscriptionId);
		}, function(res) {
			alert("error");
		});
	}
	
	$scope.refresh();
});

openaireBrokerControllers.controller('subscriptionsCtrl', function ($scope, $http, $sce, $location, $routeParams, $timeout, $base64, loginService) {
	$scope.subscriptions = {};
	
	$scope.isEmpty = function() {
		return angular.equals({}, $scope.subscriptions);
	}

	$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
	$http.get('../api/openaireBroker/subscriptions?email=' + encodeURIComponent(loginService.getUser())).then(function(res) {
		$scope.subscriptions = res.data;
	}, function(res) {
		alert("error");
	});
});


openaireBrokerControllers.controller('notificationsCtrl', function ($scope, $http, $sce, $location, $routeParams, $timeout, $base64, loginService) {
	$scope.page = null;
	$scope.nPage = $routeParams.page;
	$scope.subscrId = $routeParams.subscrId;
	
	$scope.refresh = function() {
		$http.get('../api/openaireBroker/notifications/' + $scope.subscrId + "/" + $scope.nPage + '/20').then(function(res) {
			$scope.page = res.data;
		}, function(res) {
			alert("error");
		});
	}
	
	$scope.gotoPage = function(n) {		
		$location.path('/ntf/' + n + "/" + $scope.subscrId);
	} 
		
	$scope.isAuthorHighlighted = function(author, list) {
		if (list) {
			for (var i=0; i<list.length; i++) {
				if (author.fullname + author.orcid  == list[i].fullname + list[i].orcid) {
					return true;
				}
			}
		}
		return false;
	}
	
	$scope.isSubjectHighlighted = function(subject, list) {
		if (list) {
			for (var i=0; i<list.length; i++) {
				if (subject.value == list[i].value) {
					return true;
				}
			}
		}
		return false;
	}
	
	$scope.isInstanceHighlighted = function(instance, list) {
		if (list) {
			for (var i=0; i<list.length; i++) {
				if (instance.url == list[i].url && instance.license == list[i].license && instance.hostedby == list[i].hostedby) {
					return true;
				}
			}
		}
		return false;
	}
	
	$scope.isProjectHighlighted= function(project, list) {
		if (list) {
			for (var i=0; i<list.length; i++) {
				if (project.openaireId == list[i].openaireId) {
					return true;
				}
			}
		}
		return false;
	}
	
	$scope.isPidHighlighted = function(pid, list) {
		if (list) {
			for (var i=0; i<list.length; i++) {
				if (pid.value == list[i].value && pid.type == list[i].type) {
					return true;
				}
			}
		}
		return false;
	}
	
	$scope.isDatasetHighlighted= function(dataset, list) {
		if (list) {
			for (var i=0; i<list.length; i++) {
				if (dataset.openaireId == list[i].openaireId) {
					return true;
				}
			}
		}
		return false;
	}

	$scope.isSoftwareHighlighted= function(sw, list) {
		if (list) {
			for (var i=0; i<list.length; i++) {
				if (sw.openaireId == list[i].openaireId) {
					return true;
				}
			}
		}
		return false;
	}

	
	$scope.isRelatedPublicationHighlighted= function(pub, list) {
		if (list) {
			for (var i=0; i<list.length; i++) {
				if (pub.openaireId == list[i].openaireId) {
					return true;
				}
			}
		}
		return false;
	}
	
	$scope.refresh();
});
