/**
 * LDAP attributes form section
 */
(function () {
    'use strict';

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

    attributes.$inject = ['attributesService'];

    /**
     * @param attributesService service
     */
    function attributes (service) {
        return {
            controller: controller,
            controllerAs: 'attr',
            restrict: 'E',
            scope: { },
            templateUrl: '/interface_default/admin/system/templates/ldap_attributes.directive.html'
        };

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

            // form variables
            this.fetched = false;
            this.loading = false;
            this.completed = false;
            this.statusMessage = '';
            this.ldapAttrs = [];
            this.claroAttrs = [];

            // function variables
            this.fetch = fetch;
            this.next = next;
            this.getBgHighlightClass = getBgHighlightClass;
            this.getTextHighlightClass = getTextHighlightClass;
            this.join = join;

            init();

            function init() {
                service.preload(ldap_preload.form_data, ldap_preload.date_formats, ldap_preload.date_no_year_formats);

                if (ldap_preload.form_data && ldap_preload.form_data.id) {
                    attr.completed = true;
                    // if (attr.properties.importPhotoAttr) {
                    //     attr.ldapAttrs.push({name: attr.properties.importPhotoAttr});
                    // }
                    if (attr.properties.populateOrgChartAttr) {
                        attr.ldapAttrs.push({name: attr.properties.populateOrgChartAttr});
                    }
                    if (attr.properties.populateExtranetAttr) {
                        attr.ldapAttrs.push({name: attr.properties.populateExtranetAttr});
                    }
                }
            }

            /**
             * fetch attributes for an example user
             */
            function fetch() {
                attr.loading = true;
                attr.statusMessage = '';
                return service.fetch().then(function (response) {
                    attr.fetched = response.success;
                    attr.loading = false;

                    if (!attr.fetched) {
                        attr.statusMessage = response.message;
                        return;
                    }

					// set ldap and claro metadata attributes
					attr.ldapAttrs = response.attributes.sortObject();
                    service.selectedLdap = attr.ldapAttrs[0].name;

					attr.claroAttrs = ldap_preload.metadata_map.metadata.sortArray();

                    // remove mapped attributes which does not exist in ldap user
                    var mappedLdapAttr = Object.keys(attr.properties.mappings).map(function (key) {
                        return attr.properties.mappings[key];
                    });

                    var ldapUserAttrNames = attr.ldapAttrs.map(function (item) {
                        return item.name;
                    });

                    var mappedFieldsNotInLdapUser = [];

                    mappedFieldsNotInLdapUser = mappedLdapAttr.filter(function (item) {
                        return ldapUserAttrNames.indexOf(item) === -1;
                    });

                    if (mappedFieldsNotInLdapUser.length > 0) {
                        attr.statusMessage = lmsg('admin.ldap.tools.error.mapped_fields_not_found', mappedFieldsNotInLdapUser.join(', '));

                        // remove all mapped attributes which are not exist in ldap user
                        Object.keys(attr.properties.mappings).map(function (key) {
                            if (mappedFieldsNotInLdapUser.includes(attr.properties.mappings[key]))
                                delete attr.properties.mappings[key];
                        });
                    }

                    // check if the mapping is empty
                    if (angular.equals(attr.properties.mappings, {})) {
                        attr.properties.mappings = ldap_preload.metadata_map.map;
                    }

                    // strip out any Claro fields that are already mapped, so they can't be mapped twice
                    if (attr.claroAttrs.length > 0) {
                        for (var k in attr.properties.mappings) {
                            for (var i = 0; i < attr.claroAttrs.length; i++){
                                if (attr.claroAttrs[i] == k) {
                                    attr.claroAttrs.splice(i, 1);
                                    break;
                                }
                            }
                        }
                    }

                }, function (response) {
                    attr.fetched = attr.loading = false;
                    attr.statusMessage = response.message;
                    attr.ldapAttrs.length = 0;
                });
            }

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

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

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

            /**
             * array join
             * @param value
             */
            function join(value) {
                return value.join(', ');
            }
        }
    }
}());
