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

module.directive('bsHasError', function() {
	return {
		restrict: "A",
		link: function(scope, element, attrs, ctrl) {
			element.toggleClass('has-feedback', true);
			var input = element.find('input[ng-model], select[ng-model]');
			if (input) {
				scope.$watch(function() {
					if (input.hasClass('ng-invalid')) {
						return 0;
					} else if (input.hasClass('empty')) {
						return 1;
					} else {
						return 2;
					}
				}, function(code) {
					if (code < 0) return;
					
					element.toggleClass('has-error', (code == 0));
					element.toggleClass('has-warning', (code == 1));
					element.toggleClass('has-success', (code == 2));
					
					var feedback = element.find('.form-control-feedback');
					if (feedback) {
						feedback.toggleClass('glyphicon-remove', (code == 0));
						feedback.toggleClass('glyphicon-warning-sign', (code == 1));
						feedback.toggleClass('glyphicon-ok', (code == 2));
					}
				});
			}
		}
	};
});

module.directive('ngSelectVocabularyField', function() {
	return {
		restrict: 'E',
		scope: {
            'label'            : '@',
            'vocabulary'       : '=',
            'selection'        : '=',
            'contextualParams' : '='
		},
		templateUrl: '../resources/html/addRepoApi/ngSelectVocabularyField.html',
		link: function(scope, elem, attrs) {
			scope.required = true;
			scope.selectId = 'select_' + scope.label.replace( /\s/g, "_").toLowerCase();
			
			scope.$watch('selection', function() {
				scope.contextualParams = [];
				angular.forEach(scope.vocabulary, function(term){
					if (term.name == scope.selection) {
						scope.contextualParams = term.params;
					} 					
				});				
			});
		}
	}
});

module.filter('vocabularyTerm', function() {
	return function(term) {
		if(term.desc) {
			return term.name + ' (' + term.desc + ')';
	    } else {
	    	return term.name;
	    }
	};
});

module.directive('ngSimpleEditField', function() {
	return {
		restrict: 'E',
		scope: {
            'label'         : '@',
            'regex'         : '@',
            'optional'      : '@',
            'type'          : '@',
            'selection'     : '=',
		},
		templateUrl: '../resources/html/addRepoApi/ngSimpleEditField.html',
		link: function(scope, element, attrs) {
			scope.required = (scope.optional != 'true');
			if      (scope.regex)             { scope.mypattern = new RegExp(scope.regex); }
			else if (scope.type == 'NUMBER')  { scope.mypattern = new RegExp("^[-+]?[0-9]+(\.[0-9]+)?$"); }
			else if (scope.type == 'BOOLEAN') { scope.mypattern = new RegExp("^(true|false)$"); }
			else                              { scope.mypattern = new RegExp(".+"); }
		}
	}
});

module.controller('addRepoCtrl', function ($scope, $http, $sce, $location) {
	
	common_init($scope, $http, $sce, $location)
	
	$scope.validTypes = getTypes();
	$scope.validCountries = getCountries();
	
	$scope.resetForm = function() {
		$scope.repo = {
			latitude : '0.0',
			longitude : '0.0',
			timezone : '0.0',
		};
		
		$scope.org = {};
	}
	
	$scope.registerRepo = function() {
		if (confirm('Add new datasource \n\n' + $scope.repo.officialname + '?')) {
			$scope.showSpinner();
			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
			
			$scope.org.id = 'openaire____::' + $scope.repo.id;
			$scope.repo.organizations = [$scope.org];
			
			$http.post('repo.new', $.param({
				'repo'  : JSON.stringify($scope.repo)
			})).success(function(res) {
	            	if(res) {
	            		$scope.showNotification('The Datasource has been registered');
	            		$scope.hideSpinner();
	            		$scope.done = 1;
	            	} else {
	                	$scope.hideSpinner();
	            		$scope.showError('Registration failed');
	            	}
			}).error(function(message) {
				$scope.hideSpinner();
				$scope.showError('Registration failed: ' + message);
			});
		}
	}
	
	$scope.resetForm();
});