/**
 * ldap directory settings form section
 */
(function () {
	'use strict';

	angular.module('cla.ldap.connections')
		.directive('directory', directory);

	directory.$inject = ['directoryService', 'connectionService'];

	function directory(service, connectionService) {
		return {
			controller: controller,
			controllerAs: 'dir',
			restrict: 'E',
			scope: { },
			templateUrl: '/interface_default/admin/system/templates/directory_settings.directive.html'
		}

		function controller() {
			var dir = this;
			this.properties = service.properties;

			// form variables
			this.valid = null;
			this.completed = false;
			this.loading = false;
			this.statusMessage = '';
			this.accessControlList = {
				'groups': service.properties.securityGroups,
				'ous': service.properties.ous
			};
			this.directories = ldap_preload.directories.list;
			this.settings = ldap_preload.directories.settings;
			this.dictionary = {}; // for groups/ous

			// function variables
			this.validate = validate;
			this.addGroup = addGroup;
			this.addOU = addOU;
			this.removeAccessControlEntry = removeAccessControlEntry;
			this.changeDirectory = changeDirectory;
			this.showInitialSyncTime = showInitialSyncTime;
			this.next = next;
			this.getBgHighlightClass = getBgHighlightClass;
			this.getTitleHighlightClass = getTitleHighlightClass;
			this.getSuccessMsg = getSuccessMsg;
			this.getErrorMsg = getErrorMsg;

			init();

			/**
			 * initialize
			 */
			function init() {
				service.preload(ldap_preload.form_data);
				dir.accessControlList.groups = service.properties.securityGroups;
				dir.accessControlList.ous = service.properties.ous;

				if (ldap_preload.form_data && ldap_preload.form_data.id) {
					dir.completed = true;
				}

				changeDirectory();
			}

			/**
			 * validate ldap directory settings
			 */
			function validate()	{
				if (checkAtLeastOne()) {
					dir.loading = true;
					return service.validate().then(function (response) {
						dir.valid = response.success;
						dir.loading = false;
						dir.statusMessage = (dir.valid) ?
							lmsg('admin.ldap.text.validate_status', response.details.num_users) : response.message;

						var results = response.details.status;
						for(var i in results) {
							dir.dictionary[i] = results[i];
						}
					}, function (response) {
						dir.valid = dir.loading = false;
						dir.statusMessage = response.data.message;
					});
				} else {
					dir.valid = false;
					dir.statusMessage = lmsg("admin.ldap.text.must_add_group_ou");
				}
			}

			/**
			 * add new security group
			 */
			function addGroup() {
				this.accessControlList['groups'].push('');
			}

			/**
			 * add new OU
			 */
			function addOU() {
				this.accessControlList['ous'].push('');
			}

			/**
			 * remove a security group or OU
			 * @param index
			 */
			function removeAccessControlEntry(index) {
				this.accessControlList[service.properties.grantAccessBy].splice(index, 1);
			}

			/**
			 * change directory, update settings
			 */
			function changeDirectory() {
				var value = dir.properties.directory;
				if (value == 99)
					return;

				// preset values, set inputs
				dir.properties.userTypeFilter = dir.settings[value]['user_type_filter'];
				dir.properties.userEnabledFilter = dir.settings[value]['user_enabled_filter'];
				dir.properties.usernameField = dir.settings[value]['username_field'];
				dir.properties.membershipField = dir.settings[value]['membership_field'];
				dir.properties.userGuid = dir.settings[value]['user_guid'];
			}

			/**
			 * whether we need to show the initial sync time picker
			 * @returns {boolean}
			 */
			function showInitialSyncTime() {
				var frequency = dir.properties.userDirectorySync;
				return frequency > 60;
			}

			/**
			 * progress to the next section
			 */
			function next() {
				dir.completed = true;
				$('#collapseTwo').collapse('hide');
				$('#collapse-attributes').collapse('show');
			}

			/**
			 * gets the highlight class / text class for the section header
			 */
			function getBgHighlightClass() {
				if (!dir.completed)
					return '';
				else if ((dir.valid && dir.completed) || dir.completed)
					return 'bg-success';
				else
					return 'bg-danger';
			}

            function getTitleHighlightClass() {
                if (!dir.completed)
                    return '';
                else
                    return 'text-white';
            }

			/**
			 * whether at least one ou or security group is filled in
			 * @returns {boolean}
			 */
			function checkAtLeastOne() {
				return ((dir.properties.securityGroups.length > 0 && dir.properties.securityGroups[0].length > 0)
						|| (dir.properties.ous.length > 0 && dir.properties.ous[0].length > 0));
			}

			/**
			 * gets status for each security group or ou
			 * @param key
			 */
			function getSuccessMsg(key) {
				if (dir.dictionary[key])
					return lmsg('admin.ldap.text.status') +": " + dir.dictionary[key].message + "! ( " +
						lmsg('admin.ldap.text.validate_status', dir.dictionary[key].num_users) + " )";
				return '';
			}

			/**
			 * gets status for each security group or ou
			 * @param key
			 */
			function getErrorMsg(key) {
				if (dir.dictionary[key])
					return dir.dictionary[key].message;
				return '';
			}
		}
	}
}())
