// 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.

/**
 * A combobox that is customised for the selection for article details/variants.
 * That is, it shows the order number and the additional text in the combobox field and
 * selection list. Furthermore it fires a custom event 'variantChanged' when changing
 * the selected record. This component does not require any configuration to work. However,
 * you must call 'setArticle()' on it after initialising to load its datastore. This will
 * also fire the first 'variantChanged', which your application can then react on.
 * If you like to allow an empty selection to e.g. apply a filter on all variants, you can
 * set 'allowBlank' to 'true', which allows deleting the content of the combo box. In that
 * case a 'variantChanged' event with a NULL value is fired.
 */
Ext.define('Shopware.apps.ViisonCommonVariantComboBox.view.ComboBox', {

    extend: 'Shopware.apps.ViisonCommonComboBox.view.ComboBox',
    alias: 'widget.viison_common_variant_combo_box-combo_box',
    mixins: [
        'Shopware.apps.ViisonCommonApp.Mixin',
    ],
    viisonSnippetNamespace: 'backend/viison_common_variant_combo_box/main',
    changeEventName: 'variantChanged',

    /**
     * @override
     */
    constructor: function () {
        this.fieldLabel = this.getViisonSnippet('field_label');
        this.emptyText = this.getViisonSnippet('empty_text');

        this.callParent(arguments);
    },

    /**
     * @Override
     */
    initComponent: function () {
        /**
         * Define a template and the respective conversion function for the variant selection.
         * If additionalText is set and ">0", use additionalText. Otherweise check for Configurator/Options
         * and assemble them instead. If neither is set, only the articlenumber is shown.
         */
        var variantComboboxTpl = '{number}'
            + '<tpl if="additionalText &amp;&amp; (additionalText.length &gt; 0)">'
                + ' - {additionalText}'
            + '<tpl else>'
                + '{getConfiguratorOptions:this.assembleConfiguratorOptions}'
            + '</tpl>';

        var variantComboboxTplFunctions = {
            /**
             * Assembles all Configurator/Options and strings their names together.
             * Returns an empty string if no options are set.
             */
            assembleConfiguratorOptions: function (options) {
                if (!Ext.isDefined(options) || options.length === 0) {
                    return '';
                }
                var result = ' - ';
                Ext.Array.forEach(options, function (option) {
                    result += option.name + ' ';
                });

                // Remove last blank and return result
                return result.substring(0, result.length - 1);
            },
        };

        // Set customised templates that show the additional text if present
        /* eslint-disable indent */
        this.displayTpl = Ext.create(
            'Ext.XTemplate',
            '<tpl for=".">',
                variantComboboxTpl,
            '</tpl>',
            variantComboboxTplFunctions
        );
        /* eslint-enable indent */
        this.listConfig = {
            itemTpl: Ext.create(
                'Ext.XTemplate',
                variantComboboxTpl,
                variantComboboxTplFunctions
            ),
        };

        // Create a base variant store
        this.store = Ext.create('Shopware.apps.Article.store.Variant', {
            pageSize: 2000,
        });

        this.callParent(arguments);
    },

    /**
     * @return Shopware.apps.Article.model.Variant|false
     */
    getSelectedVariant: function () {
        return this.getSelectedRecord();
    },

    /**
     * Saves the given article and, in case the article exists does already have an ID,
     * reloads the variant store data. Otherwise the store is cleared.
     *
     * @param Shopware.apps.Article.model.Article article
     */
    setArticle: function (article) {
        this.article = article;
        var store = this.getStore();
        if (!this.article || !this.article.get('id')) {
            // Clear store
            store.removeAll();
        } else if (this.article.get('isConfigurator')) {
            // Load all variants of the article
            store.getProxy().extraParams.articleId = this.article.get('id');
            store.load();
        } else {
            // Article does not have any variants, hence just add the main detail to the store
            store.loadData([
                this.article.getMainDetail().first(),
            ], false);
        }
    },

});
