/**
 * Holds data on ldap directory settings
 *
 */
(function () {
	'use strict';

	angular.module('cla.ldap.connections')
		.service('directoryService', directoryService);

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

	/**
	 *
	 * @param connectionService
	 * @param ldapResources
	 */
	function directoryService(connectionService, ldapResources) {
		var service = {
			properties: {
				directory: '1',
				userTypeFilter: '',
				userEnabledFilter: '',
				usernameField: '',
				membershipField: '',
				userGuid: '',
				grantAccessBy: 'groups',
				securityGroups: [''],
				ous: [''],
				userDirectorySync: '0',
				initialSyncTime: ''
			},

			valid: false,
			validate: validate,
			mapNames: mapNames,
			preload: preload,
			removeEmptyEntries : removeEmptyEntries
		};

		return service;

		/**
		 * validate directory settings
		 */
		function validate() {
			var connectionObject = connectionService.mapNames();
			var directoryObject = service.mapNames();
			return ldapResources.validate(connectionObject, directoryObject).$promise;
		}

		/**
		 * map js names to expected url params
		 */
		function mapNames() {
			var object = {
				'directory': {
					'type': service.properties.directory,
					'user_type_filter': service.properties.userTypeFilter,
					'user_enabled_filter': service.properties.userEnabledFilter,
					'username_field': service.properties.usernameField,
					'membership_field': service.properties.membershipField,
					'user_guid': service.properties.userGuid
				},
				'sync_interval': service.properties.userDirectorySync,
				'initial_sync_time': service.properties.initialSyncTime
			};

			// security groups or ous?
			if (service.properties.grantAccessBy === 'groups') {
				object.groups = this.removeEmptyEntries(service.properties.securityGroups);
			} else {
				object.ous = this.removeEmptyEntries(service.properties.ous);
			}


			return object;
		}

		/**
		 * preloads the object with the data passed to this function
		 */
		function preload(data) {
			if (data) {
				var object = {
					'directory': data.type,
					'userTypeFilter': data.user_type_filter,
					'userEnabledFilter': data.user_enabled_filter,
					'usernameField': data.username_field,
					'membershipField': data.membership_field,
					'userGuid': data.user_guid,
					'userDirectorySync': data.sync_interval || '0'
				};

				if (data.groups) {
					object.securityGroups = data.groups;
				}
				if (data.ous) {
					object.ous = data.ous;
					if (object.ous.length > 0)
					{
						console.log('in ous setting');
						object.grantAccessBy = 'ous';
					}
				}
				if (data.initial_sync_time) {
					object.initialSyncTime = data.initial_sync_time;
				}

				angular.extend(service.properties, object);
			}
		}

		function removeEmptyEntries(arr)
		{
			var ret = [];
			for (var i = 0; i < arr.length; i++)
			{
				if (arr[i] !== '')
					ret.push(arr[i]);
			}
			return ret;
		}
	}
}());