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

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

	connectionService.$inject = ['ldapResources'];

	/**
	 * @param ldapResources
	 */
	function connectionService(ldapResources) {
		var service = {
			properties: {
				serverUrl: '',
				netbiosName: '',
				serviceAccountDN: '',
				serviceAccountPass: '',
				searchBaseDN: '',
				passwordMethod: 1,
				dnLookupMethod: 1,
				sysCharset: 'utf-8'
			},

			connected: null,
			test: test,
			mapNames: mapNames,
			preload: preload
		};

		return service;

		/**
		 * test ldap connection
		 */
		function test() {
			var connectionObject = service.mapNames();
			return ldapResources.connectionTest(connectionObject).$promise;
		}

		/**
		 * map js names to expected url params
		 */
		function mapNames() {
			var connection_id = null;
			// add the existing connection id if it exists.
			if (ldap_preload.form_data && ldap_preload.form_data.id)
			{
				connection_id = ldap_preload.form_data.id;
			}

			var dnLookupMethod = false;
			if (service.properties.dnLookupMethod == 2)
			{
				dnLookupMethod = true;
			}

			var passwordMethod = false;
			if (service.properties.passwordMethod == 2)
			{
				passwordMethod = true;
			}

			return {
				'id' : connection_id,
				'server_url': service.properties.serverUrl,
				'base_dn': service.properties.searchBaseDN,
				'user': service.properties.serviceAccountDN,
				'password': service.properties.serviceAccountPass,
				'domain': service.properties.netbiosName,
				'bind_by_dn': passwordMethod,
				'dn_lookup_use_com': dnLookupMethod,
				'sys_charset': service.properties.sysCharset
			}
		}

		/**
		 * preloads the object with the data passed to this function
		 */
		function preload(data) {
			if (data) {
				var dnLookupMethod = 1;
				if (data.dn_lookup_use_com == true)
					dnLookupMethod = 2;

				var passwordMethod = 1;
				if (data.bind_by_dn == true)
					passwordMethod = 2;


				var object = {
					'serverUrl': data.server_url,
					'searchBaseDN': data.base_dn,
					'serviceAccountDN': data.user,
					'serviceAccountPass': data.password,
					'netbiosName': data.domain,
					'passwordMethod': passwordMethod,
					'dnLookupMethod': dnLookupMethod,
					'sysCharset': data.sys_charset
				};

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