/**
 * LDAP attributes to Claromentis metadata mapping
 */
(function () {
	'use strict';

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

	metatable.$inject = ['attributesService'];

	function metatable(attributesService) {
		return {
			bindToController: true,
			controller: controller,
			controllerAs: 'meta',
			restrict: 'E',
			scope: {
				ldap: "=",
				claro: "=",
				mappings: '=',
				fetched: '='
			},
			templateUrl: '/interface_default/admin/system/templates/metatable.directive.html'
		}

		function controller() {
			var meta = this;

            this.$onInit = function() {
                init();
            };

            meta.service = attributesService;
			// form variables
            meta.selectedLdap = meta.service.selectedLdap;
			this.selectedClaro = 0;

			// function variables
			this.remove = remove;
			this.add = add;

			function init() {
				if (meta.ldap.length > 0) {
					meta.selectedLdap = meta.ldap[0].name;
					meta.selectedClaro = 0;
				}
			}

			/**
			 * removes a row from the map table
			 * @param key
			 */
			function remove(key) {
				// splice back in the missing mapping to the claro array first
				this.claro.splice(0, 0, key);

				// re-order
				var tmp = angular.copy(this.claro.sortArray());
				this.claro.length = 0;
				for(var i in tmp) {
					if (tmp.hasOwnProperty(i)) {
						this.claro.push(tmp[i]);
					}
				}

				delete this.mappings[key];
			}

			/**
			 * adds a mapping to the map table
			 */
			function add() {
			    if (this.selectedClaro == null) // no more claro fields are available
                    return;

                if (Array.isArray(this.mappings))
                {
                    // Replace it with an object. JS arrays don't have string keys so any values it may have held were already invalid anyway
                    this.mappings = {};
                }

				this.mappings[this.claro[this.selectedClaro]] = meta.service.selectedLdap;
				// splice out claro metadata as we can only map it once.
				// ldap can be mapped multiple times
				this.claro.splice(this.selectedClaro, 1);
			}
		}
	}
}());
