/**
 * Save form
 */
(function () {
	'use strict';

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

	ldapSave.$inject = ['ldapResources', 'connectionService',
		'directoryService', 'attributesService', 'userGroupsService', 'statusService', 'growl.service'];

	/**
	 *
	 * @param resources
	 * @param connectionService
	 * @param directoryService
	 * @param attributesService
	 * @param userGroupsService
	 * @param statusService
	 * @para growlService
	 */
	function ldapSave (resources, connectionService,
					   directoryService, attributesService, userGroupsService, statusService, growlService) {
		return {
			bindToController: true,
			controller: controller,
			controllerAs: 'action',
			restrict: 'E',
			scope: {
				id: "@"
			},
			template: '<button id="save-connection" ng-model="action.id" ng-click="action.save()" name="LDAP-attr-continue" class="btn btn-primary">' + lmsg('common.save') + '</button>'
		};

		function controller () {
			var action = this;

			/**
			 * save the new (or existing) ldap connection
			 */
			this.save = function () {
				var connectionObject = connectionService.mapNames();
				var directoryObject = directoryService.mapNames();
				var attributesObject = attributesService.mapFieldNames();
				var groupMapObject = userGroupsService.mapNames();
				var statusObject = statusService.mapNames();
				$('#ldap_save_message').show();
				resources.save(
					connectionObject, directoryObject, attributesObject, groupMapObject, statusObject, action.id)
					.$promise.then(function (d) {
						if (d.success) {
							window.location.href = "/admin/system/ldap";
						} else {
							growlService.flash(d.message, d.details, true);
						}
						$('#ldap_save_message').hide();
					}, function (d) {
						console.error(d);
				});
			}
		}
	}
}());