window.AttributeVisibility = Class.create({
    config: {},

    initialize: function(config, options) {
        this.config = config;

        this.options = {
            categoryConstant: '',
            parentElementType: 'tr',
            selectedAttributeFromConfig: 'uId',
            searchPattern: 'input[name="%s"]',
            metaSearchPattern: 'input[name*="SM2__%s["]',
            fuzzySearchPattern: 'input[name*="%s"]',
            itemNamePattern: '%s'
        };

        Object.extend(this.options, options || {});
    },

    ajaxHideAttributes: function() {
        new Ajax.Request(window.www_dir + 'system/ajaxAttributeVisibility/loadConfig', {
            method:     'post',
            parameters: {
                categoryConstant: this.options.categoryConstant
            },
            onSuccess:  function (transport) {
                var json = transport.responseJSON;

                if (!is_json_response(transport, true)) {
                    return;
                }

                if (json.data) {
                    this.config = json.data;
                    this.hideAttributes();
                }
            }.bind(this)
        });
    },

    hideAttributes: function() {
        // @see ID-9257 In case of description fields 'C__CMDB__CAT__COMMENTARY_01' is ambiguous, we use a different search pattern before getting fuzzy.
        // @see ID-9026 Only use a 'fuzzy' search that matches part of the name, if no exact match was found.
        const searchPattern = [
            this.options.searchPattern,
            this.options.metaSearchPattern,
            this.options.fuzzySearchPattern
        ];

        this.config.forEach((item) => {
            let itemElement;
            const itemName = this.options.itemNamePattern;

            for (let i in searchPattern) {
                if (!searchPattern.hasOwnProperty(i)) {
                    continue;
                }

                itemElement = $('scroller').down(searchPattern[i].replace('%s', itemName.replace('%s', item[this.options.selectedAttributeFromConfig])));

                if (itemElement) {
                    if (itemElement.up(this.options.parentElementType)) {
                        itemElement.up(this.options.parentElementType).hide();
                    } else {
                        itemElement.up().hide();
                    }

                    return;
                }
            }
        });
    },
});
