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

archDB.factory('EmailSchedule', ['apiUrl', '$resource', 'ResourceMethods', 'ResourcePrototype', function (apiUrl, $resource, methods, _prototype) {
	var EmailSchedule = $resource(apiUrl('scheduled-email/:scheduledEmailId'), { scheduledEmailId: '@id' }, methods);
	angular.extend(EmailSchedule.prototype, _prototype);
	return EmailSchedule;
}]);

StockModule.factory('Status', ['apiUrl', '$resource', 'ResourceMethods', 'ResourcePrototype', function (apiUrl, $resource, methods, _prototype) {
	var Status = $resource(apiUrl('statuses/:statusId'), { statusId: '@id' }, methods);
	angular.extend(Status.prototype, _prototype);
	return Status;
}]);

Admin.controller('AdminCalendarCtrl', ['$scope', '$http', 'ErrorsHandler', 'Messenger', '$timeout', function ($scope, $http, ErrorsHandler, Messenger, $timeout) {

	$scope.save = function (data, success_message) {
		if ($scope.saving) return false;
		if (!data) data = $scope.data;
		$scope.saving = true;

		$http.post($scope.post_url, data)
			.success(function (response) {
				$scope.success = true;
				$scope.error_message = false;
				$scope.saving = false;
				angular.extend($scope.data, response || {});
				if (success_message) Messenger(success_message);
			})
			.error(function (a, b) {
				$scope.success = false;
				$scope.error_message = true;
				$scope.saving = false;
				ErrorsHandler(a, b);
			})
	};

	$scope.enable = function () {
		$scope.save({ enabled: true }, 'Calendar module is now enabled.');
	};

	$scope.disable = function () {
		$scope.save({ enabled: false }, 'Calendar module is now disabled.');
	};

}]);
Admin.controller('AdminContractsCtrl', ['$scope', '$http', 'ErrorsHandler', '$window', function ($scope, $http, ErrorsHandler, $window) {

	$scope.remove = function () {
		$http.delete($scope.delete_url)
			.success(function () {
				$window.location = $scope.redirect;
			})
			.error(ErrorsHandler);
	};

}]);
Admin.controller('AdminEmailScheduleCtrl', ['$scope', 'EmailSchedule', 'ErrorsHandler', '$paginator', '$uibModal', function ($scope, EmailSchedule, ErrorsHandler, $paginator, $uibModal) {

	$paginator = angular.copy($paginator);
	$scope.paginator = $paginator;

	$scope.$watch('filters', function () {
		$scope.load();
	});

	$scope.load = function () {
		EmailSchedule.get({}, function (response) {
			$scope.data = response.data;
			$paginator.setFromResponse(response);
		}, ErrorsHandler);
	};

}]);
Admin.controller('AdminEmailSettingsCtrl', ['$scope', '$http', 'ErrorsHandler', '$window', function ($scope, $http, ErrorsHandler, $window) {

	$scope.toggle = function (url) {
		$http.post(url)
			.success(function (response) {
				$scope.data.enabled = response.enabled;
				$scope.success = response.message;
			})
			.error(ErrorsHandler);
	};

	$scope.remove = function () {
		$http.delete($scope.delete_url)
			.success(function () {
				$window.location = $scope.redirect;
			})
			.error(ErrorsHandler);
	};

}]);
Admin.controller('AdminEventCtrl', ['$scope', function ($scope) {

	$scope.allModelFields = [];
	$scope.conditions = [];
	$scope.commands = [];
	$scope.modelFields = [];
	$scope.comparisonOptions = [{
		id: "=",
		name: "="
	}];

	$scope.$watch('data.model', function (value) {
		$scope.modelFields = ($scope.allModelFields.hasOwnProperty(value))
			? $scope.allModelFields[value]
			: [];


	});

	$scope.addCondition = function () {
		$scope.conditions.push({});
	};

	$scope.addCommand = function () {
		$scope.commands.push({});
	};



	// 	$scope.addCondition = function() {

	// 		var num= $scope.data.num++;
	// 		var conditions_body= $scope.data.conditions_body;
	// 		var condition_template= "hola";

	// 		conditions_body= condition_template;
	// 		$scope.data.num= num;
	// 		alert("hello");
	// 		// var modalInstance = $uibModal.open({
	// 		// 	templateUrl: 'admin/settings/statuses/modals/delete.html',
	// 		// 	controller: 'AdminStatusDeleteCtrl',
	// 		// 	resolve: {
	// 		// 		options: function() {
	// 		// 			return {
	// 		// 				'redirect' : $scope.redirect,
	// 		// 				'url'      : $scope.delete_url
	// 		// 			};
	// 		// 		}
	// 		// 	}
	// 		// });

	// 	};

}]);
Admin.controller('AdminGamificationCtrl', ['$scope', '$http', 'ErrorsHandler', 'Messenger', '$timeout', function ($scope, $http, ErrorsHandler, Messenger, $timeout) {

	$scope.save = function (data, success_message) {
		if ($scope.saving) return false;
		if (!data) data = $scope.data;
		$scope.saving = true;

		$http.post($scope.post_url, data)
			.success(function (response) {
				$scope.success = true;
				$scope.error_message = false;
				$scope.saving = false;
				angular.extend($scope.data, response || {});
				if (success_message) Messenger(success_message);
			})
			.error(function (a, b) {
				$scope.success = false;
				$scope.error_message = true;
				$scope.saving = false;
				ErrorsHandler(a, b);
			})
	};

	$scope.enable = function () {
		$scope.save({ enabled: true }, 'Gamification module is now enabled.');
	};

	$scope.disable = function () {
		$scope.save({ enabled: false }, 'Gamification module is now disabled.');
	};
}]);
Admin.controller('AdminGroupCtrl', ['$scope', '$http', 'ErrorsHandler', '$window', function ($scope, $http, ErrorsHandler, $window) {

	/**
	 *	watch the $scope data var
	 *
	 *	@var Object
	 */

	$scope.$watch('data', function () {
		$scope.selectedUsers = $scope.jsonify($scope.data.users);
	});

	$scope.jsonify = function (collectionIn) {
		var returnArray = [];
		angular.forEach(collectionIn, function (key, value) {
			key = angular.toJson(key);
			returnArray.push(key);
		});
		return returnArray;
	};

	$scope.numberify = function (collectionIn) {
		var returnArray = [];
		angular.forEach(collectionIn, function (key, value) {
			key = Number(key);
			returnArray.push(key);
		});
		return returnArray;
	};

	/**
	 *	Create a new group
	 *
	 *	@return null
	 */
	$scope.save = function () {
		if ($scope.saving) return false;
		$scope.saving = true;

		$scope.selectedUsers = $scope.numberify($scope.selectedUsers);
		$scope.data.users = $scope.selectedUsers;

		$http.post($scope.post_url, $scope.data)
			.success(function (response) {
				$scope.saving = false;
				$window.location = $scope.redirect_url;
			})
			.error(ErrorsHandler);
	};

	/**
	 * 	Update the group
	 *
	 *	@return null
	 */
	$scope.update = function () {
		if ($scope.saving) return false;
		$scope.saving = true;
		$scope.success = false; // Reset success state

		$scope.selectedUsers = $scope.numberify($scope.selectedUsers);
		$scope.data.users = $scope.selectedUsers;

		$http.put($scope.post_url, $scope.data)
			.success(function (response) {
				$scope.saving = false;
				$scope.success = true; // Set success to show message
				angular.extend($scope.data, response || {});
			})
			.error(function(data, status) {
				$scope.success = false; // Ensure success is false on error
				ErrorsHandler(data, status);
			});
	};

	/**
	 *	Check to see if a permission has been selected or not
	 *
	 *	@return null
	 */
	$scope.permissionChecked = function (id) {
		return _.find($scope.data.permissions, function (el) { return el == id; })
			? true : false;
	};

	/**
	 *	Toggle a permissions, between its selected state or not selected state.
	 *
	 * 	@return null
	 */
	$scope.togglePermission = function (id) {
		if ($scope.permissionChecked(id)) {

			$scope.data.permissions = _.reject($scope.data.permissions, function (item) {
				return item == id;
			});

			return;
		}

		$scope.data.permissions.push(id);
	};


}]);
Admin.controller('AdminLdapCtrl', ['$scope', '$http', 'ErrorsHandler', 'Messenger', '$timeout', function ($scope, $http, ErrorsHandler, Messenger, $timeout) {

	$scope.save = function (data, success_message) {
		if ($scope.saving) return false;
		if (!data) data = $scope.data;
		$scope.saving = true;

		$http.post($scope.post_url, data)
			.success(function (response) {
				$scope.success = true;
				$scope.error_message = false;
				$scope.saving = false;
				angular.extend($scope.data, response || {});
				if (success_message) Messenger(success_message);
			})
			.error(function (a, b) {
				$scope.success = false;
				$scope.error_message = true;
				$scope.saving = false;
				ErrorsHandler(a, b);
			})
	};

	$scope.enable = function () {
		$scope.save({ enabled: true }, 'LDAP module is now enabled.');
	};

	$scope.disable = function () {
		$scope.save({ enabled: false }, 'LDAP module is now disabled.');
	};

	$scope.test = function (url) {
		if ($scope.testing) return false;
		$scope.testing = true;

		$http.post(url, $scope.data)
			.success(function (response) {
				$scope.testing = false;

				if (response.success) {
					Messenger('Successfully connected to the LDAP server.');
					$scope.test_success = true;
					$timeout(function () { $scope.test_success = false; }, 5000);
				}
				else {
					Messenger('Unable to connect to the LDAP server');
					$scope.test_failed = true;
					$timeout(function () { $scope.test_failed = false; }, 5000);
				}
			})
			.error(function (a, b) {
				$scope.testing = false;
				$scope.test_failed = true;
				$timeout(function () { $scope.test_failed = false; }, 5000);
				ErrorsHandler(a, b);
			});
	};
}]);
Admin.controller('AdminRestCtrl', ['$scope', '$http', 'ErrorsHandler', '$window', function ($scope, $http, ErrorsHandler, $window) {

	$scope.remove = function () {
		$http.delete($scope.delete_url)
			.success(function () {
				$window.location = $scope.redirect;
			})
			.error(ErrorsHandler);
	};

}]);
Admin.controller('AdminStatusCtrl', ['$scope', '$uibModal', function ($scope, $uibModal) {

	$scope.remove = function () {
		var modalInstance = $uibModal.open({
			templateUrl: 'admin/settings/statuses/modals/delete.html',
			controller: 'AdminStatusDeleteCtrl',
			resolve: {
				options: function () {
					return {
						'redirect': $scope.redirect,
						'url': $scope.delete_url
					};
				}
			}
		});
	};

}]);

Admin.controller('AdminStatusDeleteCtrl', ['$scope', '$uibModalInstance', 'ErrorsHandler', '$http', '$window', 'options', function ($scope, $uibModalInstance, ErrorsHandler, $http, $window, options) {

	$scope.data = {};

	$scope.cancel = function () {
		$uibModalInstance.dismiss('cancel');
	};

	$scope.submit = function () {
		if (!$scope.data.status_id) return false;

		$http.delete(options.url, { params: $scope.data })
			.success(function () {
				$uibModalInstance.close();
				$window.location = options.redirect;
			})
			.error(ErrorsHandler);
	};

}]);
Admin.controller('AdminTaskTemplatesCtrl', ['$scope', 'Template', 'TemplateItem', 'ErrorsHandler', '$paginator', '$uibModal', '$q', function ($scope, Template, TemplateItem, ErrorsHandler, $paginator, $uibModal, $q) {

	$paginator = angular.copy($paginator);
	$scope.paginator = $paginator;
	$scope.filters = {};

	$paginator.setOnPageChange(function (page) {
		$scope.load(page);
	});

	$scope.$watch('filters', function () {
		$scope.load();
	}, true);

	$scope.load = function (page) {

		var filters = angular.copy($scope.filters);
		filters.page = (!page) ? 1 : page;

		Template.get(filters, function (response) {
			$scope.templates = response.data;
			$paginator.setFromResponse(response);
		}, ErrorsHandler);
	};

	$scope.load();

	/**
	 * Updates a template
	 */
	$scope.updateTemplate = function (template, name) {
		var d = $q.defer();

		Template.update({ id: template.id, name: name }, function (response) {
			d.resolve();
		}, function (a, b) {
			ErrorsHandler(a, b);
			d.reject('Error');
		});

		return d.promise;
	};

	/**
	 * Delete a template
	 */
	$scope.delete = function (template) {
		Template.delete({ templateId: template.id }, function () {
			$scope.templates = _.reject($scope.templates, function (el) {
				return el.id == template.id;
			});
		}, ErrorsHandler);
	};


	/**
	 * Edit a template
	 */
	$scope.edit = function (template) {

		var modalInstance = $uibModal.open({
			templateUrl: 'admin/modals/task-template.html',
			controller: 'AdminTemplateModal',
			resolve: {

				'template': function () { return template; },
				'action': function () { return 'edit'; }
			}
		});

		modalInstance.result.then(function (template) {
			angular.forEach($scope.templates, function (t, i) {
				if (t.id === template.id) {
					$scope.templates[i] = template;
				}
			});
		});

	};

	/**
	 * Displays the create new template modal.
	 */
	$scope.showTemplateModal = function () {

		var modalInstance = $uibModal.open({
			templateUrl: 'admin/modals/task-template.html',
			controller: 'AdminTemplateModal',
			resolve: {
				'action': function () { return 'create'; },
				'template': function () {
					return { 'name': '', 'priority': '', 'task_types': [] };
				}
			}
		});

		modalInstance.result.then(function (template) {
			$scope.templates.push(template);
		});
	};

	/**
	 * Updates a template item
	 */
	$scope.updateTemplateItem = function (item, description) {
		var d = $q.defer();

		TemplateItem.update({ id: item.id, description: description }, function (response) {
			d.resolve();
		}, function (a, b) {
			ErrorsHandler(a, b);
			d.reject('Error');
		});

		return d.promise;
	};

	/**
	 * Delete a template item
	 */
	$scope.deleteItem = function (template, item) {
		TemplateItem.delete({ templateItemId: item.id }, function () {
			template.items = _.reject(template.items, function (el) {
				return el.id == item.id;
			});
		}, ErrorsHandler);
	};

	/**
	 * Displays the create new template item modal.
	 */
	$scope.showTemplateItemModal = function (template) {

		var modalInstance = $uibModal.open({
			templateUrl: 'admin/modals/task-template-item.html',
			controller: 'AdminTemplateItemModal',
			resolve: {
				template: function () {
					return template;
				}
			}
		});

		modalInstance.result.then(function (item) {
			template.items.push(item);
		});
	};


}]);
Admin.controller('AdminTemplateItemModal', ['$scope', '$uibModalInstance', 'TemplateItem', 'template', 'ErrorsHandler', function ($scope, $uibModalInstance, TemplateItem, template, ErrorsHandler) {
	$scope.data = {
		template_id: template.id
	};

	$scope.save = function () {
		TemplateItem.save($scope.data, function (response) {
			$uibModalInstance.close(response);
		}, ErrorsHandler);
	};

	$scope.cancel = function () {
		$uibModalInstance.dismiss('cancel');
	};
}]);
Admin.controller('AdminTemplateModal', ['$scope', '$uibModalInstance', 'Template', 'ErrorsHandler', 'action', 'template', function ($scope, $uibModalInstance, Template, ErrorsHandler, action, template) {

	$scope.data = template;
	$scope.action = action;

	$scope.save = function () {
		if (action == 'create')

			Template.save($scope.data, function (response) {
				$uibModalInstance.close(response);
			}, ErrorsHandler);

		else if (action == 'edit')
			Template.update($scope.data, function (response) {
				$uibModalInstance.close(response);
			}, ErrorsHandler);
	};

	$scope.cancel = function () {
		$uibModalInstance.dismiss('cancel');
	};



	/**
	 *	Check to see if a taskType has been selected or not
	 *
	 *	@return null
	 */
	$scope.taskTypeChecked = function (taskType) {
		return _.find($scope.data.task_types, function (el) { return el.id == taskType.id; })
			? true : false;
	};

	/**
	 *	Toggle a taskType, between its selected state or not selected state.
	 *
	 * 	@return null
	 */
	$scope.toggleTaskType = function (taskType) {

		if ($scope.taskTypeChecked(taskType)) {

			$scope.data.task_types = _.reject($scope.data.task_types, function (item) {
				return item.id == task_type.id;
			});

			return;
		}

		$scope.data.task_types.push(taskType);
	};


}]);
Admin.controller('AdminUserModal', ['$scope', '$uibModalInstance', 'user', 'User', 'ErrorsHandler', function ($scope, $uibModalInstance, user, User, ErrorsHandler) {
	$scope.data = user;
	$scope.account_types = [{ name: 'Local Account', value: 'local' }, { name: 'LDAP - Active Directory', value: 'ldap', disabled: !$scope.data.id }];

	$scope.save = function () {
		if ($scope.data.id) {
			User.update($scope.data, function (response) {
				$uibModalInstance.close(response);
			}, ErrorsHandler);
		}
		else {
			User.save($scope.data, function (response) {
				$uibModalInstance.close(response);
			}, ErrorsHandler);
		}
	};

	$scope.cancel = function () {
		$uibModalInstance.dismiss('cancel');
	};
}]);
Admin.controller('AdminUsersCtrl', ['$scope', 'User', 'ErrorsHandler', '$paginator', '$uibModal', function ($scope, User, ErrorsHandler, $paginator, $uibModal) {

	$paginator = angular.copy($paginator);
	$scope.paginator = $paginator;
	$scope.filters = {};

	$paginator.setOnPageChange(function (page) {
		$scope.load(page);
	});

	$scope.$watch('filters', function () {
		$scope.load();
	}, true);

	$scope.load = function (page) {

		var filters = angular.copy($scope.filters);
		filters.page = (!page) ? 1 : page;

		User.get(filters, function (response) {
			$scope.users = response.data;
			$paginator.setFromResponse(response);
		}, ErrorsHandler);
	};

	$scope.load();

	$scope.showUserModal = function (user) {

		var modalInstance = $uibModal.open({
			templateUrl: 'admin/modals/user.html',
			controller: 'AdminUserModal',
			resolve: {
				user: function () {
					return user || { account_type: 'local', active: 1 };
				}
			}
		});

		modalInstance.result.then(function (_user) {
			if (user) {
				angular.extend(user, _user || {});
			} else {
				$scope.users.push(_user);
			}
		});
	};

}]);
