// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

Ext.define('Shopware.apps.ViisonPickwareCommonArticlePropertyTypes.view.TypeSelectionField', {

    extend: 'Ext.form.field.ComboBox',
    alias: 'widget.viison_pickware_common_article_property_types-type_selection_field',
    mixins: [
        'Shopware.apps.ViisonCommonApp.Mixin',
    ],
    viisonSnippetNamespace: 'backend/viison_pickware_common_article_property_types/main',
    labelWidth: 250,
    allowBlank: true,
    editable: false,
    autoSelect: false,
    forceSelection: true,
    submitEmptyText: false,
    multiSelect: true,
    queryMode: 'local',
    valueField: 'id',
    displayField: 'name',

    /**
     * @override
     */
    initComponent: function () {
        this.fieldLabel = this.getViisonSnippet('type_selection_field/label');
        this.helpText = this.getViisonSnippet('type_selection_field/help_text');

        // Create and load the store
        this.store = Ext.create('Shopware.apps.ViisonPickwareCommonArticlePropertyTypes.store.PropertyType', {
            sorters: [
                { property: 'name', direction: 'ASC' },
            ],
        });
        this.store.on('load', function () {
            if (this.getValue()) {
                // Remove field values that no longer exist in the store
                var filteredValue = Ext.Array.filter(this.getValue(), function (value) {
                    return this.store.findExact('id', value) !== -1;
                }, this);
                this.setValue(filteredValue);
            }
        }, this);
        this.store.load();

        this.callParent();
    },

    /**
     * @override
     */
    createHelp: function () {
        // Create td element as a wrapper
        var row = new Ext.Element(document.createElement('td'));
        row.set({
            width: 24,
            valign: 'top',
        });
        row.appendTo(this.inputRow);

        // Create icon and add it to the wrapper
        var editIcon = new Ext.Element(document.createElement('span'));
        editIcon.set({
            cls: 'sprite-pencil',
            style: 'margin: 6px 0 0 8px; z-index: 1; display: block; cursor: pointer;',
            'data-qtip': this.getViisonSnippet('type_selection_field/edit_types/tooltip'),
        });
        editIcon.addListener('click', function () {
            this.fireEvent('editTypes', this);
        }, this);
        editIcon.appendTo(row);

        this.callParent(arguments);
    },

});
