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

/**
 * The main form panel containing all input fields to create/edit the mapping
 * of the shipping method to a dispatch provider product.
 */
//{namespace name="backend/viison_shipping_common_shipping/shipping"}
Ext.define('Shopware.apps.ViisonShippingCommonShipping.view.edit.MappingPanel', {

    /**
     * Extend from the standard ExtJS 4.
     */
    extend: 'Ext.form.Panel',

    /**
     * List of short aliases for class names. Most useful for defining xtypes for widgets.
     */
    alias: 'widget.shipping-viison-shipping-common-mapping-panel',

    /**
     * An optional extra CSS class that will be added to this component's Element.
     */
    cls: Ext.baseCSSPrefix + 'shipping-viison-shipping-common-mapping-panel',

    /**
     * Component layout definition.
     */
    layout: {
        align: 'stretch',
        type: 'vbox'
    },

    /**
     * Set flex to 100%.
     */
    flex: 1,

    /**
     * Add padding.
     */
    bodyPadding: '10 10 0 10',

    /**
     * Remove the border.
     */
    border: 0,

    /**
     * Disable collapse mode.
     */
    collapsible: false,

    defaults: {
        flex: 1,
        labelWidth: 150
    },

    /**
     * Contains all snippets for the view component.
     */
    snippets: {
        labels: {
            product: '{s name="mapping_panel/labels/product"}{/s}',
            exportDocument: '{s name="mapping_panel/labels/export_document"}{/s}'
        },
        products: {
            none: '{s name="mapping_panel/products/none"}{/s}'
        }
    },

    /**
     * The main initializer registering events and adding view components.
     */
    initComponent: function() {
        var me = this;

        me.items = me.getItems();

        // Prepare stores
        if (me.productStore.find('id', 0) === -1) {
            // Add 'none' product
            me.productStore.insert(0, {
                id: 0,
                name: me.snippets.products.none,
                code: ''
            });
        }
        if (!me.record.get('clone') && !me.record.phantom) {
            // Edit existing mapping
            me.productMappingStore.getProxy().extraParams = {
                dispatchId: me.record.internalId
            };
            me.productMappingStore.load({
                callback: function(records, operation, success) {
                    if (success) {
                        me.setValues();
                    }
                }
            });
        }

        me.callParent(arguments);

        // Determine value for new and cloned shipping methods
        if (me.record.get('clone') && me.record.data.id != 0 && me.productMappingStore.data.keys.indexOf(me.record.data.id) == -1) {
            // Create temporary store
            var tmpStore = Ext.create(me.productMappingStoreClass);
            tmpStore.getProxy().extraParams = {
                dispatchId: me.record.data.id
            };
            // Load mapping of the cloned dispatch id
            tmpStore.load({
                callback: function(records, operation, success) {
                    if (success && records.length > 0 && records[0].data.productId !== undefined) {
                        me.setMappingValues(records[0]);
                    } else {
                        me.setMappingValues(null);
                    }
                    me.productMapping = undefined;
                }
            });
        } else if (me.record.get('clone') || me.record.phantom) {
            me.setMappingValues(null);
        }
    },

    /**
     * Returns the items that this component is made up of. Can be overridden in derived classed to add more items.
     *
     * @return array
     */
    getItems: function() {
        var me = this;
        return [
            me.createMappingItem(),
            me.createExportDocumentItem()
        ];
    },

    /**
     * Creates a combobox to select the desired UPS product.
     *
     * @return The created combobox item.
     */
    createMappingItem: function() {
        return {
            xtype: 'combobox',
            name: 'product',
            fieldLabel: Ext.String.format(this.snippets.labels.product, this.dispatchServiceProviderName),
            valueField: 'id',
            displayField: 'name',
            queryMode: 'local',
            mode: 'local',
            required: false,
            editable: false,
            allowBlank: true,
            store: this.productStore,
            listeners: {
                change: function (field, newValue) {
                    this.fireEvent('changeProductComboBox', this, newValue);
                },
                scope: this,
            }
        };
    },

    /**
     * Creates a checkbox to select enable/disable the generation of export documents
     * for the current dispatch method.
     *
     * @return The created checkbox item.
     */
    createExportDocumentItem: function() {
        var me = this;

        this.createExportDocumentCheckbox = Ext.create('Ext.form.field.Checkbox', {
            name: 'exportDocumentRequired',
            fieldLabel: me.snippets.labels.exportDocument,
            required: false,
            checked: false,
            hidden: !me.exportDocumentEnabled,
            listeners: {
                change: function (field, newValue) {
                    this.fireEvent('changeCreateExportDocumentCheckBox', this, newValue);
                },
                scope: this,
            },
            flex: 1,
            labelWidth: 150,
        });

        return this.createExportDocumentCheckbox;
    },

    /**
     * Sets the record values to the corresponding input fields.
     */
    setValues: function() {
        if (this.productMappingStore.data.length === 1) {
            // Select product
            this.productMapping = this.productMappingStore.data.items[0];
            this.setMappingValues(this.productMapping);
        } else {
            this.setMappingValues(null);
        }
    },

    /**
     * Sets the values contained in the given mapping or, if the mapping is null,
     * the default values, to the form field.
     *
     * @param productMapping The mapping, which contains the values, which will be set to the form fields.
     */
    setMappingValues: function(productMapping) {
        var values = {
            product: 0
        };

        if (productMapping !== null) {
            // Find the mapped product
            var i = this.productStore.findExact('id', productMapping.get('productId'));
            var product = this.productStore.getAt(i);
            if (product !== undefined) {
                values.product = product.data.id;
            }

            // Set export document and other individual attributes
            Ext.iterate(productMapping.data, function(key, value) {
                if (!(key in ['dispatchId', 'productId'])) {
                    values[key] = value;
                }
            });
        }

        // Set the values in the form
        this.getForm().setValues(values);
        this.fireEvent('mappingValuesSetInForm', this);
    },

});
