var orgsModule = angular.module('orgs', ['ngRoute', 'checklist-model']);

orgsModule.service('vocabulariesService', function($http) {
    this.vocs = {};
    this.getVocs = function(f) {
   		if (Object.keys(this.vocs).length === 0) {
   			call_http_get($http, 'api/vocabularies', function(res) {
	    		this.vocs = res.data;
	    		f(angular.copy(this.vocs));
			});
   		} else {
   			f(this.vocs);
   		}
    };
});

orgsModule.factory('suggestionInfo', function($http) {
    var info = { data : {} };
    
    var getInfo = function() { return info; };
    
    var updateInfo = function(callback) {
    	call_http_get($http, 'api/organizations/suggestionsInfo', function(res) {
	   		info.data = res.data;
	   		if (callback) { callback(info); }
		});
    };
   
    return {
    	getInfo: getInfo,
    	updateInfo: updateInfo
    };
    
});

orgsModule.controller('menuCtrl', function ($scope, suggestionInfo) {
	$scope.info = suggestionInfo.getInfo();
	suggestionInfo.updateInfo(null);
});

orgsModule.directive('selectOrgModal', function($http, $timeout) {
	return {
		restrict: 'E',
		scope: {
			'modalId'      : '@',
			'filterStatus' : '@',
			'selectedOrg'  : '=',
			'onSelect'     : '&'
		},
		templateUrl: 'resources/html/parts/select_org.modal.html',
		link: function(scope, element, attrs, ctrl) {
			scope.searchOrgs = {};
			scope.searchText = '';
 			scope.searchValue = '';
			
			scope.search = function(text, page, size) {
				scope.searchOrgs = {};
								
				call_http_get($http, 'api/organizations/search/' + page + '/' + size + '?status='+ scope.filterStatus + '&q=' + text, function(res) {
					scope.searchValue = text;
					scope.searchOrgs = res.data;
				});
			}
			
			scope.selectOrg = function() {
				if (scope.onSelect) {
					scope.onSelect();
				}
			}
		}
	}
});

orgsModule.directive('advancedMenuItem', function($http, $location, $route) {
	return {
		restrict: 'E',
		scope: {
			'menu'        : '@',
			'description' : '@',
			'url'         : '@',
			'badge'       : '@',
			'first'       : '@'
		},
		templateUrl: 'resources/html/parts/advanced_menu_item.html',
		link: function(scope, element, attrs, ctrl) {}
     }
});

orgsModule.directive('resolveConflictsModal', function($http, $route, $window) {
	return {
		restrict: 'E',
		scope: {
			'openNewOrg'    : '@',
			'modalId'       : '@',
			'orgs'          : '=',
			'selectedOrgs'  : '='
		},
		templateUrl: 'resources/html/parts/resolve_conflicts.modal.html',
		link: function(scope, element, attrs, ctrl) {
			scope.selectOrg = function(org) {
				var sel = angular.copy(org);
				if (scope.selectedOrgs.length == 0) { sel.show = 'success'; }
				else                                { sel.show = 'info'; }
				scope.selectedOrgs.push(sel); 
				org.show = 'hidden';
			}

			scope.reset = function() {
				scope.selectedOrgs = [];
				angular.forEach(scope.orgs, function(org) { org.show = 'secondary'; });
			}
			
			scope.mergeGroup = function() {
				var ids = [];
				angular.forEach(scope.selectedOrgs, function(o, pos) {
					ids.push(o.id);
				});
				if (ids.length > 0) {
					call_http_post($http, 'api/organizations/conflicts/fix/similar', ids, function(res) {
						$('#' + scope.modalId).modal('hide');
						if (scope.openNewOrg == '1') {
							$('#' + scope.modalId).on('hidden.bs.modal', function (e) { 
								var oldLoc = $window.location;
								$window.location.assign('#!/edit/0/' + res.data[0]); 
								var newLoc = $window.location;
								if (oldLoc == newLoc) $route.reload();
							});
						} else { 
							$('#' + scope.modalId).on('hidden.bs.modal', function (e) { $route.reload(); });
						}
					}); 
				}
			}
			
			scope.invalidateGroup = function() {
				var ids = [];
				angular.forEach(scope.selectedOrgs, function(o, pos) {
					ids.push(o.id);
				});
				if (ids.length > 0) {
					call_http_post($http, 'api/organizations/conflicts/fix/different', ids, function(res) {
						$('#' + scope.modalId).modal('hide');
						$('#' + scope.modalId).on('hidden.bs.modal', function (e) { $route.reload(); });
					}); 
				}
			}
		}
	}
});
		
orgsModule.directive('orgFormMetadata', function($http, $location, $route, $routeParams) {
	return {
		restrict: 'E',
		scope: {
			'org'          : '=',
			'vocabularies' : '=',
			'mode'         : '@',  // insert_full, insert_pending, update_simple, update_full, approve, readonly, not_authorized
			'infoMethod'   : '&'
		},
		templateUrl: 'resources/html/parts/org_metadata.form.html',
		link: function(scope, element, attrs, ctrl) {
			scope.newRelation = {};
			scope.newRelType = '';
							
			scope.resetSelectedRelation = function() {
				scope.newRelation = {};
			}
		
			scope.addNewRelation = function() {
				scope.org.relations.push({
					'relatedOrgId'   : scope.newRelation.id,
					'relatedOrgName' : scope.newRelation.name,
					'type'           : scope.newRelType
				});
				scope.newRelation = {};
				scope.newRelType = '';
			}
			
			scope.save = function() {
				call_http_post($http, 'api/organizations/save', scope.org, function(res) {
					if      (scope.mode == 'insert')        { $location.url('/edit/1/' + res.data[0]);    }
					else if (scope.mode == 'approve')       { $location.url('/edit/3/' + res.data[0]);    }
					else if ($routeParams.msg == 2)         { $route.reload(); }
					else                                    { $location.url('/edit/2/' + res.data[0]); }
				}); 
			}
		}
     }
});

orgsModule.directive('orgDetails', function($http, $location, $route) {
	return {
		restrict: 'E',
		scope: {
			'org'      : '=',
			'orgTitle' : '@',
			'show'     : '@'
		},
		templateUrl: 'resources/html/parts/org_details.html',
		link: function(scope, element, attrs, ctrl) {}
     }
});

orgsModule.directive('orgResultsPage', function($http, $location, $route) {
	return {
		restrict: 'E',
		scope: {
			'searchMessage' : '@',
			'orgs'          : '=',
			'nextFunction'  : '&',
			'prevFunction'  : '&',
			'onSelect'      : '&',
			'selectedOrg'   : '=',
			'mode'          : '@',
			'showStatus'    : '@',
			'showNDups'     : '@'
		},
		templateUrl: 'resources/html/parts/org_results_page.html',
		link: function(scope, element, attrs, ctrl) {
			scope.selectOrg = function(o) {
				o.selected = true;

				scope.selectedOrg.id = o.id;
				scope.selectedOrg.name = o.name;
				scope.selectedOrg.type = o.type;
				scope.selectedOrg.city = o.city;
				scope.selectedOrg.country = o.country;
				scope.selectedOrg.acronyms = o.acronyms;
				scope.selectedOrg.urls = o.urls;
				scope.selectedOrg.status = o.status;
				
				if (scope.onSelect) {
					scope.onSelect(); 
				}
				
			}
		}
     }
});

orgsModule.directive('orgDuplicates', function($http, $location, $route) {
	return {
		restrict: 'E',
		scope: {
			'orgId'        : '@',
			'duplicates'   : '=',
			'showButtons'  : '@',
			'readonly'     : '@',
			'saveFunction' : '&'
		},
		templateUrl: 'resources/html/parts/org_duplicates.html',
		link: function(scope, element, attrs, ctrl) {
			scope.newDuplicate = {};
			
			scope.addDuplicate = function() {
				
				for (var i = 0; i < scope.duplicates.length; i++) {
					if (scope.duplicates[i].oaOriginalId == scope.newDuplicate.id) {
						alert("The selected organization has been already added !!!");
						return;
					}				
				}
				
				scope.duplicates.push({
					'localId'         : scope.orgId,
					'oaOriginalId'    : scope.newDuplicate.id,
					'oaName'          : scope.newDuplicate.name,
					'oaAcronym'       : scope.newDuplicate.acronyms.join(),
					'oaCountry'       : scope.newDuplicate.country,
					'oaUrl'           : scope.newDuplicate.urls.join(),
					'oaCollectedFrom' : '',
					'createdBy'       : currentUser(),
					'relType'         : 'suggested'
				});
			}
		}
     }
});

orgsModule.directive('orgConflicts', function($http, $window, $location, $route, $q) {
	return {
		restrict: 'E',
		scope: {
			'org'         : '=',   
			'conflicts'   : '=',
			'showButtons' : '@'
		},
		templateUrl: 'resources/html/parts/org_conflicts.html',
		link: function(scope, element, attrs, ctrl) {
			scope.candidateConflicts = [];
			scope.selectedConflicts = [];
			scope.newConflict = {};
			
			scope.addConflict = function() {
				scope.conflicts.push({
					'id'     : scope.newConflict.id,
					'name'   : scope.newConflict.name,
					'type'   : scope.newConflict.type,
					'city'   : scope.newConflict.city,
					'country': scope.newConflict.country
				});		
			}
			
			scope.prepareConflictsModal = function() {
				scope.candidateConflicts = [];
				scope.selectedConflicts = [];
				
				var gets = [ $http.get('api/organizations/get?id=' + scope.org.id) ];
				angular.forEach(scope.conflicts, function(c) { gets.push($http.get('api/organizations/get?id=' + c.id)); });
				
				$q.all(gets).then(function(responses) {
					scope.candidateConflicts = responses.map((resp) => resp.data);
					angular.forEach(scope.candidateConflicts, function(org) { org.show = 'secondary'; });
				});
			}
			
			scope.resolveConflicts = function(merge) {
				if (scope.conflicts.length > 0) {
					if (merge && !confirm("You are merging " + (scope.conflicts.length + 1) + " organization(s).\n\nDo you confirm?" )) {
						return;
					}
			
					if (!merge && !confirm("You are marking as different  " + (scope.conflicts.length + 1) + " organization(s).\n\nDo you confirm?" )) {
						return;
					}
			
					var ids = [scope.org.id];
					angular.forEach(scope.conflicts, function(o, pos) { ids.push(o.id); });
					
					if (merge) {
						call_http_post($http, "api/organizations/conflicts/fix/similar", ids, function(res) { 
							if (res.data[0] == scope.org.id) {
								$route.reload();
							} else {
								$window.location.assign('#!/edit/0/' + res.data[0]); 
							}
						}); 
					} else {
						call_http_post($http, "api/organizations/conflicts/fix/different", ids, function(res) { $route.reload(); }); 
					}
				} else { 
					alert('Invalid group !!!');
				}
			}
		}
     }
});

orgsModule.directive('orgNote', function($http) {
	return {
		restrict: 'E',
		scope: {
			'org' : '=',
			'note': '=',
			'saveFunction' : '&'
		},
		templateUrl: 'resources/html/parts/org_note.html',
		link: function(scope, element, attrs, ctrl) { 
		}
     }
});

orgsModule.directive('orgJournal', function($http) {
	return {
		restrict: 'E',
		scope: {
			'org' : '=',
			'logs': '='
		},
		templateUrl: 'resources/html/parts/org_journal.html',
		link: function(scope, element, attrs, ctrl) {}
     }
});


orgsModule.config(function($routeProvider) {
	$routeProvider
		.when('/search',                               { templateUrl: 'resources/html/pages/search/search.html',           controller: 'searchCtrl' })
		.when('/searchResults/:page/:size/:text*',     { templateUrl: 'resources/html/pages/search/searchResults.html',    controller: 'searchResultsCtrl' })
		.when('/countries/:mode',                      { templateUrl: 'resources/html/pages/search/browse.html',           controller: 'countriesCtrl' })
		.when('/byCountry/:page/:size/:status/:code*', { templateUrl: 'resources/html/pages/search/resultsByCountry.html', controller: 'byCountryCtrl' })
		.when('/types/:mode',                          { templateUrl: 'resources/html/pages/search/browse.html',           controller: 'typesCtrl' })
		.when('/byType/:page/:size/:status/:type*',    { templateUrl: 'resources/html/pages/search/resultsByType.html',    controller: 'byTypeCtrl' })
		.when('/edit/:msg/:id*',                       { templateUrl: 'resources/html/pages/edit/edit.html',               controller: 'showEditCtrl' })
		.when('/new',                                  { templateUrl: 'resources/html/pages/advanced/new.html',            controller: 'newOrgCtrl' })
		.when('/pendings/:country',                    { templateUrl: 'resources/html/pages/advanced/pendingOrgs.html',    controller: 'pendingOrgsCtrl' })
		.when('/duplicates/:country',                  { templateUrl: 'resources/html/pages/advanced/duplicates.html',     controller: 'duplicatesCtrl' })
		.when('/conflicts/:country',                   { templateUrl: 'resources/html/pages/advanced/conflicts.html',      controller: 'conflictsCtrl' })
		.when('/users',                                { templateUrl: 'resources/html/pages/admin/users.html',             controller: 'usersCtrl' })
		.when('/sysconf',                              { templateUrl: 'resources/html/pages/admin/sysConf.html',           controller: 'sysConfCtrl' })
		.when('/utils',                                { templateUrl: 'resources/html/pages/admin/utils.html',             controller: 'utilsCtrl' })
		.when('/lastImport',                           { templateUrl: 'resources/html/pages/admin/lastImport.html',        controller: 'lastImportCtrl' })
		.when('/persistentOrgs',                       { templateUrl: 'resources/html/pages/admin/persistentOrgs.html',    controller: 'persistentOrgsCtrl' })
		.otherwise({ redirectTo: '/search' });
});

orgsModule.filter('escape', function() {
	return function(input) {
		return encodeURIComponent(encodeURIComponent(input));
	}; 
});

orgsModule.filter('unescape', function() {
	return function(input) {
		return decodeURIComponent(input);
	};
});

orgsModule.controller('newOrgCtrl', function ($scope, $http, $routeParams, $location, vocabulariesService) {
	$scope.org = {
		"id": "",
		"name": "",
		"type": null,
		"lat": 0.0,
		"lng": 0.0,
		"city": "",
		"country": "",
		"source": "user",
		"otherIdentifiers": [],
		"otherNames": [],
		"relations": [],
		"acronyms": [],
		"urls": [],
		"relations": []
	};
	$scope.adminMode = adminMode();
	$scope.vocabularies = {};
	vocabulariesService.getVocs(function(vocs) { $scope.vocabularies = vocs; });
});

orgsModule.controller('searchCtrl', function ($scope, $location) {
	$scope.searchText = '';
	$scope.search = function() {
		if ($scope.searchText) {
			$location.url('/searchResults/0/50/' + encodeURIComponent(encodeURIComponent($scope.searchText)));
		} else {
			$location.url('/searchResults/0/50/_');
		}
	}
});

orgsModule.controller('searchResultsCtrl', function ($scope, $http, $routeParams, $location) {
	$scope.searchText = '';	
	if ($routeParams.text != '_') {
		$scope.searchText = decodeURIComponent($routeParams.text);
	}
	$scope.orgs = {};

	call_http_get($http, 'api/organizations/search/' + $routeParams.page + '/' + $routeParams.size + '?q=' + $scope.searchText, function(res) { $scope.orgs = res.data; });
	
	$scope.prev = function() {
		if ($scope.searchText) {
			$location.url('/searchResults/' + ($scope.orgs.number - 1) + '/' + $scope.orgs.size + '/' + encodeURIComponent($scope.searchText));
		} else {
			$location.url('/searchResults/' + ($scope.orgs.number - 1) + '/' + $scope.orgs.size + '/_');
		}
	}
	
	$scope.next = function() {
		if ($scope.searchText) {
			$location.url('/searchResults/' + ($scope.orgs.number + 1) + '/' + $scope.orgs.size + '/' + encodeURIComponent($scope.searchText));
		} else {
			$location.url('/searchResults/' + ($scope.orgs.number + 1) + '/' + $scope.orgs.size + '/_');
		}
	}
});

orgsModule.controller('countriesCtrl', function ($scope, $http, $routeParams) {
	
	$scope.title = 'Countries';
	$scope.field = 'Country';
	$scope.resultsBasePath = '/byCountry'
	$scope.entries = [];
	$scope.mode = $routeParams.mode;
	
	call_http_get($http, 'api/organizations/browse/countries', function(res) { $scope.entries = res.data; });
	
});

orgsModule.controller('byCountryCtrl', function ($scope, $http, $routeParams, $location) {
	$scope.fieldValue = decodeURIComponent($routeParams.code);
	$scope.orgs = {};
	
	call_http_get($http, 'api/organizations/byCountry/' + $routeParams.status + '/' + $routeParams.code + '/' + $routeParams.page + '/' + $routeParams.size, function(res) { $scope.orgs = res.data; });
	
	$scope.prev = function() {
		$location.url('/byCountry/' + ($scope.orgs.number - 1) + '/' + $scope.orgs.size + '/' + $routeParams.status + '/' + encodeURIComponent($scope.fieldValue));
	}
	
	$scope.next = function() {
		$location.url('/byCountry/' + ($scope.orgs.number + 1) + '/' + $scope.orgs.size + '/' + $routeParams.status + '/' + encodeURIComponent($scope.fieldValue));
	}

});

orgsModule.controller('typesCtrl', function ($scope, $http, $routeParams) {
	$scope.title = 'Organization types';
	$scope.field = 'Organization type';
	$scope.resultsBasePath = '/byType'
	$scope.entries = [];
	$scope.mode = $routeParams.mode;
	
	call_http_get($http, 'api/organizations/browse/types', function(res) { $scope.entries = res.data; });
});

orgsModule.controller('byTypeCtrl', function ($scope, $http, $routeParams, $location) {
	
	$scope.fieldValue = $routeParams.type;
	
	$scope.orgs = {};
	
	call_http_get($http, 'api/organizations/byType/' + $routeParams.status + '/' + $routeParams.type + '/' + $routeParams.page + '/' + $routeParams.size, function(res) { $scope.orgs = res.data; });
	
	$scope.prev = function() {
		$location.url('/byType/' + ($scope.orgs.number - 1) + '/' + $scope.orgs.size + '/' + $routeParams.status + '/' + encodeURIComponent($scope.fieldValue));
	}
	
	$scope.next = function() {
		$location.url('/byType/' + ($scope.orgs.number + 1) + '/' + $scope.orgs.size + '/' + $routeParams.status + '/' + encodeURIComponent($scope.fieldValue));
	}
});


orgsModule.controller('showEditCtrl', function ($scope, $http, $routeParams, $route, $location, $timeout, $window, $filter, vocabulariesService) {
	$scope.orgId = $routeParams.id;
	$scope.org = {};
	$scope.duplicates = [];
	$scope.conflicts = [];
	$scope.info = {};
	$scope.currentTab = 1
	$scope.vocabularies = {};
	$scope.adminMode = adminMode();
	
	$scope.getInfo = function() {
    	call_http_get($http, 'api/organizations/info?id=' + $scope.orgId, function(res) { $scope.info = res.data; });
    };
	
	$scope.gotoTab = function(tab) {
		$scope.org = {};
		call_http_get($http, 'api/organizations/get?id=' + $scope.orgId, function(res) {
			res.data.relations = $filter('orderBy')(res.data.relations, ['type','relatedOrgName'], false);
			$scope.org = res.data;
		});
		
		if (tab == 2) {
			$scope.duplicates = [];
			call_http_get($http, 'api/organizations/duplicates?id=' + $scope.orgId, function(res) { $scope.duplicates = res.data; });
		} else if (tab == 3) {
			$scope.conflicts = [];
			call_http_get($http, 'api/organizations/conflicts?id=' + $scope.orgId, function(res) { $scope.conflicts = res.data; });			
		} else if (tab == 4) {
			$scope.note = {};
			call_http_get($http, 'api/organizations/note?id=' + $scope.orgId, function(res) { $scope.note = res.data; });			
		} else if (tab == 5) {
			$scope.logs = [];
			call_http_get($http, 'api/organizations/journal?id=' + $scope.orgId, function(res) { $scope.logs = res.data; });			
		}
		
		
		$scope.currentTab = tab;
	}
	
	$scope.saveDuplicates = function() {
		call_http_post($http, 'api/organizations/duplicates', $scope.duplicates, function(res) {
			$scope.getInfo();
			alert('Duplicates updated !!!');
			$scope.duplicates = res.data;
		});
	}
	
	$scope.saveNote = function() {
		call_http_post($http, 'api/organizations/note', $scope.note, function(res) {
			$scope.getInfo();
			alert("Note saved !!!");
			$scope.note = res.data;	
		}); 
	}
	
	vocabulariesService.getVocs(function(vocs) { $scope.vocabularies = vocs; });
	$scope.getInfo();
	$scope.gotoTab(1);

	if      ($routeParams.msg == 1) { $scope.message = 'New organization registered !!!';     }
	else if ($routeParams.msg == 2) { $scope.message = 'Organization updated !!!';            }
	else if ($routeParams.msg == 3) { $scope.message = 'Pending organization registered !!!'; }
	else                            { $scope.message = '';                                    }
	$window.scrollTo(0, 0);
	
	$timeout(function() { $scope.message = ''; }, 3000);

});

orgsModule.controller('pendingOrgsCtrl', function ($scope, $http, $routeParams, $location, suggestionInfo) {
	$scope.info = suggestionInfo.getInfo();
	$scope.loading = true;
	$scope.orgs = [];
	$scope.country = $routeParams.country;
	$scope.sortProperty = 'name';
	$scope.sortReverse = false;
	
	$scope.getInfo = function() {
		suggestionInfo.updateInfo(function(info) { 
			if ($scope.country == '_') {
				var found = '';
				angular.forEach(info.data.byCountry, function(c) {
					if (!found && c.nPendingOrgs > 0) {
						found = c.code;
					}
				});
				if (found) { $location.url('/pendings/' + found); }
			}
		});
	};
	
	$scope.sortBy = function(sortProperty) {
		$scope.sortReverse = ($scope.sortProperty == sortProperty) ? !$scope.sortReverse : false;
		$scope.sortProperty = sortProperty;
	};

	$scope.refresh = function() {
		$scope.orgs = [];
		$scope.loading = true;
			
		if ($scope.country != '_') {
			call_http_get($http, 'api/organizations/byCountry/suggested/' + $scope.country, function(res) { $scope.orgs = res.data; $scope.loading = false; });
		}
		$scope.getInfo();
	}
	
	$scope.refresh();
});

orgsModule.controller('duplicatesCtrl', function ($scope, $http, $routeParams, $location, $timeout, $route, suggestionInfo) {
	$scope.info = suggestionInfo.getInfo();
	$scope.loading = true;
	$scope.duplicates = [];
	$scope.country = $routeParams.country;
	$scope.currentOrg = {};
	$scope.currentOrgDetails = {};
	$scope.sortProperty = 'name';
	$scope.sortReverse = false;
	
	$scope.prepareDuplicatesModal = function(org) {
		$scope.currentOrg = org;
		$scope.currentOrgDetails = {};
		$scope.currentDuplicates = [];
		
		call_http_get($http, 'api/organizations/get?id=' + org.id,        function(res) { $scope.currentOrgDetails = res.data; });
		call_http_get($http, 'api/organizations/duplicates?id=' + org.id, function(res) { $scope.currentDuplicates = res.data; });
	};
	
	$scope.getInfo = function() {
		suggestionInfo.updateInfo(function(info) { 
			if ($scope.country == '_') {
				var found = '';
				angular.forEach(info.data.byCountry, function(c) {
					if (!found && c.nDuplicates > 0) {
						found = c.code;
					}
				});
				if (found) { $location.url('/duplicates/' + found); }
			}
		});	
	};
	
	$scope.saveCurrentDuplicates = function() {
		
		call_http_post($http, 'api/organizations/duplicates', $scope.currentDuplicates, function(res) {
			
			$scope.getInfo();
			
			$scope.currentOrg.numberOfDuplicates = 0;
			for (var i=0; i<res.data.length; i++) {
				if (res.data[i].relType == 'suggested') {
					$scope.currentOrg.numberOfDuplicates++;
				}
			}
			$scope.currentDuplicates = [];
			
			$timeout(function() { 
				if ($scope.duplicates.length > 1) {
					$route.reload();
				} else {
					$location.url('/duplicates/_');
				}
			}, 600);
			
		});
	};
		
	$scope.sortBy = function(sortProperty) {
		$scope.sortReverse = ($scope.sortProperty == sortProperty) ? !$scope.sortReverse : false;
		$scope.sortProperty = sortProperty;
	};
	
	$scope.refresh = function() {
		$scope.duplicates = [];
		$scope.loading = true;		
		
		if ($scope.country != '_') {
			call_http_get($http, 'api/organizations/duplicates/byCountry/' + $scope.country, function(res) { $scope.duplicates = res.data; $scope.loading = false; });
		}
		$scope.getInfo();
	}
	
	$scope.refresh();
});

orgsModule.controller('conflictsCtrl', function ($scope, $http, $routeParams, $location, $route, $q, suggestionInfo) {
	$scope.info = suggestionInfo.getInfo();
	$scope.loading = true;
	$scope.conflicts = [];
	$scope.country = $routeParams.country;
	$scope.orgs = [];
	$scope.newConflict = {};
	$scope.currentGroup = [];
	
	$scope.addConflict = function() {
		$scope.currentGroup.push({
			'id'     : $scope.newConflict.id,
			'name'   : $scope.newConflict.name,
			'type'   : $scope.newConflict.type,
			'city'   : $scope.newConflict.city,
			'country': $scope.newConflict.country
		});		
	}
	
	$scope.prepareAddConflictModal = function(list) {
		$scope.currentGroup = list;
	};
	
	$scope.prepareConflictsModal = function(list) {
		$scope.orgs = [];
		$scope.selectedOrgs = [];
		
		var gets = list.map((o) => $http.get('api/organizations/get?id=' + o.id));
		
		$q.all(gets).then(function(responses) {
			$scope.orgs = responses.map((resp) => resp.data);
			angular.forEach($scope.orgs, function(org) { org.show = 'secondary'; });
		});
	}
	
	$scope.resolveConflictGroup = function(group, merge) {
		if (group.length > 1) {
			if (merge && !confirm("You are merging " + group.length + " organization(s).\n\nDo you confirm?" )) {
				return;
			}
	
			if (!merge && !confirm("You are marking as different  " + group.length + " organization(s).\n\nDo you confirm?" )) {
				return;
			}
	
			var ids = [];
			angular.forEach(group, function(o, pos) { ids.push(o.id); });
			
			var url = "api/organizations/conflicts/fix/";
			if (merge) { url += "similar";   }
			else       { url += "different"; }
			
			call_http_post($http, url, ids, function(res) { $route.reload(); }); 
		} else { 
			alert('Invalid group !!!');
		}
	}
	
	$scope.getInfo = function() {
		suggestionInfo.updateInfo(function(info) { 
			if ($scope.country == '_') {
				var found = '';
				
				angular.forEach(info.data.byCountry, function(c) {
					if (!found && c.nConflicts > 0) {
						found = c.code;
					}
				});
				if (found) { $location.url('/conflicts/' + found); }
			}
		});
	};
	
	$scope.refresh = function() {
		$scope.conflicts = [];
		$scope.loading = true;
		
		if ($scope.country != '_') {
			call_http_get($http, 'api/organizations/conflicts/byCountry/' + $scope.country, function(res) { $scope.conflicts = res.data; $scope.loading = false; });
		}
		$scope.getInfo();
	}
	
	$scope.refresh();
});

orgsModule.controller('sysConfCtrl', function ($scope, $http, $timeout, $route) {
	$scope.sysconf = {};
		
	call_http_get($http, 'api/sysconf', function(res) { $scope.sysconf = res.data; });
	
	$scope.saveConf = function() {
		// I use force_http_post because call_http_post could be disabled if the system is in readonly mode 
		force_http_post($http, 'api/sysconf', $scope.sysconf, function(res) { 
			$scope.sysconf = res.data; 
			alert("Configuration saved !"); 
			window.location.reload();
		});
	}
	
});	

orgsModule.controller('lastImportCtrl', function ($scope, $http) {
	$scope.lastImport = {};

	$scope.refresh = function() {
		call_http_get($http, 'api/lastImportStatus', function(res) { $scope.lastImport = res.data; });
	}
	
	$scope.refresh();
});	

orgsModule.controller('persistentOrgsCtrl', function ($scope, $http) {
	$scope.orgs = {};

	$scope.refresh = function() {
		call_http_get($http, 'api/persistentOrgs', function(res) { $scope.orgs = res.data; });
	}
	
	$scope.addPersistentOrg = function(id) {
		call_http_post($http, 'api/persistentOrgs', [ id ], function(res) { $scope.orgs = res.data; });
	}
	
	$scope.deletePersistentOrg = function(id) {
		if (confirm("Are you sure ?")) {
			call_http_delete($http, 'api/persistentOrgs?id=' + id, function(res) { $scope.orgs = res.data; });
		}
	}	
	
	$scope.refresh();
});	

orgsModule.controller('utilsCtrl', function ($scope, $http) {
	
	$scope.fulltextIndexMessage = '';
	$scope.consistencyCheckMessage = '';
	$scope.invalidSuggestedCountriesMessage = '';
	$scope.suggestionImportMessage = '';
	$scope.cacheMessage = '';

	$scope.refreshFulltextIndex = function() {
		$scope.fulltextIndexMessage = '...';
		call_http_get($http, 'api/refreshFulltextIndex', function(res) { $scope.fulltextIndexMessage = res.data[0]; });
	}
	
	$scope.performConsistencyCheck = function() {
		$scope.consistencyCheckMessage = '...';
		call_http_get($http, 'api/performConsistencyCheck', function(res) { $scope.consistencyCheckMessage = res.data[0]; });
	}
	
	$scope.verifyCountriesInSuggestions = function() {
		$scope.invalidSuggestedCountriesMessage = '...';
		call_http_get($http, 'api/verifyCountriesInSuggestions', function(res) { $scope.invalidSuggestedCountriesMessage = res.data[0]; });
	}
	
	$scope.restartSuggestionsImport = function() {
		$scope.suggestionImportMessage = '...';
		call_http_get($http, 'api/restartSuggestionsImport', function(res) { $scope.suggestionImportMessage = res.data[0]; });
	}
	
	$scope.clearCache = function() {
		$scope.cacheMessage = '...';
		call_http_get($http, 'api/clearCache', function(res) { $scope.cacheMessage = res.data[0]; });
	}
	
});	



orgsModule.controller('usersCtrl', function ($scope, $http, vocabulariesService) {
	$scope.users = [];
	$scope.vocs = {};
	$scope.currentUser = {};
	$scope.superAdminMode = superAdminMode();
	
	$scope.vocabularies = {};
	vocabulariesService.getVocs(function(vocs) { $scope.vocabularies = vocs; });
	
	call_http_get($http, 'api/users', function(res) { $scope.users = res.data; });
		
	$scope.setCurrentUser = function(user) {
		angular.copy(user, $scope.currentUser);
		if (!$scope.currentUser.role || $scope.currentUser.role == 'PENDING') {		
			$scope.currentUser.role = 'USER';
		}
	}
	
	$scope.saveUser = function(user) {
		call_http_post($http, 'api/users', user, function(res) { $scope.users = res.data; });
	}
	
	$scope.deleteUser = function(email) {
		if (confirm("Are you sure ?")) {
			call_http_delete($http, 'api/users?email=' + email, function(res) { $scope.users = res.data; });
		}
	}
});
