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

// {namespace name="backend/viison_dhl_shipping/shipping"}
Ext.define('Shopware.apps.ViisonDHLShipping.view.edit.MappingPanel', {

    extend: 'Shopware.apps.ViisonShippingCommonShipping.view.edit.MappingPanel',

    alias: 'widget.viison-dhl-shipping-mapping-panel',

    /**
     * Contains all snippets for the view component.
     */
    customSnippets: {
        items: {
            visualAgeCheck: {
                label: '{s name="mapping_panel/items/visual_age_check/label"}{/s}',
                help: '{s name="mapping_panel/items/visual_age_check/help"}{/s}',
                options: {
                    noMinimumAge: '{s name="mapping_panel/items/visual_age_check/options/no_minimum_age"}{/s}',
                    minimumAge16: '{s name="mapping_panel/items/visual_age_check/options/minimum_age_16"}{/s}',
                    minimumAge18: '{s name="mapping_panel/items/visual_age_check/options/minimum_age_18"}{/s}',
                },
            },
            personalHandover: {
                label: '{s name="mapping_panel/items/personal_handover/label"}{/s}',
                help: '{s name="mapping_panel/items/personal_handover/help"}{/s}',
            },
            parcelOutletRouting: {
                label: '{s name="mapping_panel/items/parcel_outlet_routing/label"}{/s}',
                help: '{s name="mapping_panel/items/parcel_outlet_routing/help"}{/s}',
            },
            postalDeliveryDutyPaid: {
                label: '{s name="mapping_panel/items/postal_delivery_duty_paid/label"}{/s}',
                help: '{s name="mapping_panel/items/postal_delivery_duty_paid/help"}{/s}',
            },
            closestDroppointDelivery: {
                label: '{s name="mapping_panel/items/closest_droppoint_delivery/label"}{/s}',
                help: '{s name="mapping_panel/items/closest_droppoint_delivery/help"}{/s}',
            },
            incotermCombobox: {
                label: '{s name="mapping_panel/items/incoterm_combobox/label"}{/s}',
                help: '{s name="mapping_panel/items/incoterm_combobox/help"}{/s}',
            },
            frankaturCombobox: {
                label: '{s name="mapping_panel/items/frankatur_combobox/label"}{/s}',
                help: '{s name="mapping_panel/items/frankatur_combobox/help"}{/s}',
            },
            endorsementTypeCombobox: {
                label: '{s name="mapping_panel/items/endorsement_type_combobox/label"}{/s}',
                help: '{s name="mapping_panel/items/endorsement_type_combobox/help"}{/s}',
                options: {
                    notSpecified: '{s name="mapping_panel/items/endorsement_type_combobox/options/not_specified"}{/s}',
                    immediate: '{s name="mapping_panel/items/endorsement_type_combobox/options/immediate"}{/s}',
                    abandonment: '{s name="mapping_panel/items/endorsement_type_combobox/options/abandonment"}{/s}',
                },
            },
            identCheck: {
                label: '{s name="mapping_panel/items/ident_check/label"}{/s}',
                help: '{s name="mapping_panel/items/ident_check/help"}{/s}',
            },

            signedForByRecipient: {
                label: '{s name="mapping_panel/items/signed_for_by_recipient/label"}{/s}',
                help: '{s name="mapping_panel/items/signed_for_by_recipient/help"}{/s}',
            },
        },
    },

    initComponent: function () {
        this.incotermStore = Ext.getStore('viisonDHLIncotermStore') || Ext.create('Shopware.apps.ViisonDHLTermsOfTrade.store.Incoterm');
        this.frankaturStore = Ext.getStore('viisonDHLFrankaturStore') || Ext.create('Shopware.apps.ViisonDHLTermsOfTrade.store.Frankatur');

        this.callParent(arguments);
    },

    /**
     * @override
     */
    getItems: function () {
        return this.callParent(arguments).concat([
            this.createVisualAgeCheckCombobox(),
            this.createIdentCheckCombobox(),
            this.createPersonalHandoverCheckbox(),
            this.createParcelOutletRoutingCheckbox(),
            this.createPostalDeliveryDutyPaidCheckbox(),
            this.createClosestDroppointDeliveryCheckbox(),
            this.createSaturdayDeliveryForDHLExpress(),
            this.createIncotermCombobox(),
            this.createFrankaturCombobox(),
            this.createInsuredAmountForDHLExpress(),
            this.createEndorsementTypeCombobox(),
            this.createSignedForByRecipientCheckbox(),
        ]);
    },

    /**
     * @override
     */
    createMappingItem: function () {
        /**
         * Grope products by country name.
         *
         * NOTE: The template can't be created with groupedProductsByCountry flag set for product retrieve,
         *       because EXTJs has a limitation for templates and store in combobox.
         *       The combo's underlying boundlist (the abstractview actually) attempts to
         *       reconcile view nodes (using the itemselector which for boundlists is x-boundlist-item)
         *       with the store records on all add/update/delete actions. If you're creating more nodes than you have
         *       store items and the underlying view's reconciliation effort is choking.
         *
         * BIG NOTE:  // {literal} var templateText = '{[this.groupProductsByCountryName(values)]}'; // {/literal}
         *           this is a standard approach for minified, see https://github.com/VIISON/minimal-smartyness for more info.
         *
         * @type Ext.XTemplate
         */

        // {literal}
        var templateText = '{[this.groupProductsByCountryName(values)]}';
        // {/literal}
        var template = Ext.create('Ext.XTemplate',
            templateText,
            {
                groupProductsByCountryName: function (values) {
                    var html = '';
                    var country = null;

                    if (!values) {
                        return null;
                    }

                    // The first result is 'Empty Selection' so we are setting it at the top of the combobox
                    html += '<div style ="padding-left: 12px;" class="x-boundlist-item">' + values[0].name + '</div>';
                    for (var i = 1, length = values.length; i < length; i += 1) {
                        if (values[i] && values[i].displayCountryName) {
                            // Create title only when we switch from country product group to another
                            if (country !== values[i].displayCountryName) {
                                // Create the grouping title for products, example. Germany, Austria ...
                                html += '<p style="color: #656565; padding: 8px 8px 4px 2px; font-weight: bold; margin: 0 8px 0 8px; border-bottom: 1px solid rgba(34,36,38,.15);">' + values[i].displayCountryName + '</p>';
                            }
                            country = values[i].displayCountryName;
                            html += '<div style ="padding-left: 12px;" class="x-boundlist-item">' + values[i].name + '</div>';
                        }
                    }

                    // To make sure that the memory will be deallocate
                    // (EXT JS has shown some weird behaviors with templates and memory issues)
                    values = null;
                    country = null;

                    return html;
                },
            });

        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,
            tpl: template,
            listeners: {
                change: function (field, newValue) {
                    this.fireEvent('changeProductComboBox', this, newValue);
                },
                scope: this,
            },
        };
    },

    /**
     * Creates a combobox to configure the visual age check service option.
     *
     * @return { Ext.form.field.ComboBox }
     */
    createVisualAgeCheckCombobox: function () {
        this.visualAgeCheck = Ext.create('Ext.form.field.ComboBox', {
            name: 'visualAgeCheck',
            fieldLabel: this.customSnippets.items.visualAgeCheck.label,
            helpText: this.customSnippets.items.visualAgeCheck.help,
            valueField: 'value',
            displayField: 'text',
            emptyText: this.customSnippets.items.visualAgeCheck.options.noMinimumAge,
            queryMode: 'local',
            mode: 'local',
            editable: false,
            labelWidth: 150,
            store: Ext.create('Ext.data.SimpleStore', {
                fields: [
                    'text', 'value',
                ],
                data: [
                    [this.customSnippets.items.visualAgeCheck.options.noMinimumAge, null],
                    [this.customSnippets.items.visualAgeCheck.options.minimumAge16, 16],
                    [this.customSnippets.items.visualAgeCheck.options.minimumAge18, 18],
                ],
            }),
            listeners: {
                change: this.onMinimumAgeActive,
                scope: this,
            },
        });

        return this.visualAgeCheck;
    },

    /**
     * Creates a combobox to configure the ident check service option.
     *
     * @return { Ext.form.field.ComboBox }
     */
    createIdentCheckCombobox: function () {
        this.identCheckAge = Ext.create('Ext.form.field.ComboBox', {
            name: 'identCheckAge',
            fieldLabel: this.customSnippets.items.identCheck.label,
            helpText: this.customSnippets.items.identCheck.help,
            valueField: 'value',
            displayField: 'text',
            emptyText: this.customSnippets.items.visualAgeCheck.options.noMinimumAge,
            queryMode: 'local',
            mode: 'local',
            editable: false,
            labelWidth: 150,
            store: Ext.create('Ext.data.SimpleStore', {
                fields: [
                    'text', 'value',
                ],
                data: [
                    [this.customSnippets.items.visualAgeCheck.options.noMinimumAge, null],
                    [this.customSnippets.items.visualAgeCheck.options.minimumAge16, 16],
                    [this.customSnippets.items.visualAgeCheck.options.minimumAge18, 18],
                ],
            }),
            listeners: {
                change: this.onIdentCheckActive,
                scope: this,
            },

        });

        return this.identCheckAge;
    },

    /**
     * Creates a checkbox to configure the personal handover service option.
     *
     * @return { Ext.form.field.Checkbox }
     */
    createPersonalHandoverCheckbox: function () {
        this.personalHandover = Ext.create('Ext.form.field.Checkbox', {
            name: 'personalHandover',
            fieldLabel: this.customSnippets.items.personalHandover.label,
            helpText: this.customSnippets.items.personalHandover.help,
            required: false,
            checked: false,
            labelWidth: 150,
        });

        return this.personalHandover;
    },

    /**
     * @returns { Ext.form.field.ComboBox }
     */
    createIncotermCombobox: function () {
        this.incotermCombobox = Ext.create('Ext.form.field.ComboBox', {
            name: 'incoterm',
            fieldLabel: this.customSnippets.items.incotermCombobox.label,
            helpText: this.customSnippets.items.incotermCombobox.help,
            valueField: 'name',
            displayField: 'description',
            queryMode: 'local',
            mode: 'local',
            editable: false,
            emptyText: '-',
            store: this.incotermStore,
            flex: 1,
            labelWidth: 150,
        });

        return this.incotermCombobox;
    },

    /**
     * @returns { Ext.form.field.ComboBox }
     */
    createFrankaturCombobox: function () {
        this.frankaturCombobox = Ext.create('Ext.form.field.ComboBox', {
            name: 'frankatur',
            fieldLabel: this.customSnippets.items.frankaturCombobox.label,
            helpText: this.customSnippets.items.frankaturCombobox.help,
            valueField: 'name',
            displayField: 'description',
            queryMode: 'local',
            mode: 'local',
            editable: false,
            emptyText: '-',
            store: this.frankaturStore,
            flex: 1,
            labelWidth: 150,
        });

        return this.frankaturCombobox;
    },

    /**
     * @returns { Ext.form.field.Checkbox }
     */
    createSaturdayDeliveryForDHLExpress: function () {
        this.saturdayDeliveryForExpress = Ext.create('Ext.form.field.Checkbox', {
            name: 'isSaturdayDelivery',
            fieldLabel: '{s name="mapping_panel/items/saturday_delivery_dhl_express/label"}{/s}',
            required: false,
            checked: false,
            labelWidth: 150,
        });

        return this.saturdayDeliveryForExpress;
    },

    /**
     * @returns { Ext.form.field.Checkbox }
     */
    createInsuredAmountForDHLExpress: function () {
        this.insuredCheckBoxForDHLExpress = Ext.create('Ext.form.field.Checkbox', {
            name: 'isInsured',
            fieldLabel: '{s name="mapping_panel/items/insured_value_dhl_express/label"}{/s}',
            helpText: '{s name="mapping_panel/items/insured_value_dhl_express/help"}{/s}',
            required: false,
            checked: false,
            labelWidth: 150,
        });

        return this.insuredCheckBoxForDHLExpress;
    },

    /**
     * Creates a checkbox to configure the retail outlet routing service option.
     *
     * @return { Ext.form.field.Checkbox }
     */
    createParcelOutletRoutingCheckbox: function () {
        this.parcelOutletRouting = Ext.create('Ext.form.field.Checkbox', {
            name: 'parcelOutletRouting',
            fieldLabel: this.customSnippets.items.parcelOutletRouting.label,
            helpText: this.customSnippets.items.parcelOutletRouting.help,
            required: false,
            checked: false,
            labelWidth: 150,
        });

        return this.parcelOutletRouting;
    },

    /**
     * Creates a checkbox to configure the postal delivery duty paid service option.
     *
     * @return { Ext.form.field.Checkbox }
     */
    createPostalDeliveryDutyPaidCheckbox: function () {
        this.postalDeliveryDutyPaid = Ext.create('Ext.form.field.Checkbox', {
            name: 'postalDeliveryDutyPaid',
            fieldLabel: this.customSnippets.items.postalDeliveryDutyPaid.label,
            helpText: this.customSnippets.items.postalDeliveryDutyPaid.help,
            required: false,
            checked: false,
            labelWidth: 150,
        });

        return this.postalDeliveryDutyPaid;
    },

    /**
     * Creates a checkbox to configure the closest droppoint delivery service option.
     *
     * @return { Ext.form.field.Checkbox }
     */
    createClosestDroppointDeliveryCheckbox: function () {
        this.closestDroppointDelivery = Ext.create('Ext.form.field.Checkbox', {
            name: 'closestDroppointDelivery',
            fieldLabel: this.customSnippets.items.closestDroppointDelivery.label,
            helpText: this.customSnippets.items.closestDroppointDelivery.help,
            required: false,
            checked: false,
            labelWidth: 150,
        });

        return this.closestDroppointDelivery;
    },

    /**
     * Creates a combobox to configure the type of endorsement.
     *
     * @return { Ext.form.field.Checkbox }
     */
    createEndorsementTypeCombobox: function () {
        this.endorsementTypeCombobox = Ext.create('Ext.form.field.ComboBox', {
            name: 'endorsementType',
            fieldLabel: this.customSnippets.items.endorsementTypeCombobox.label,
            helpText: this.customSnippets.items.endorsementTypeCombobox.help,
            valueField: 'value',
            displayField: 'text',
            emptyText: this.customSnippets.items.endorsementTypeCombobox.options.notSpecified,
            queryMode: 'local',
            mode: 'local',
            editable: false,
            labelWidth: 150,
            store: Ext.create('Ext.data.SimpleStore', {
                fields: [
                    'text', 'value',
                ],
                data: [
                    [this.customSnippets.items.endorsementTypeCombobox.options.notSpecified, null],
                    [this.customSnippets.items.endorsementTypeCombobox.options.immediate, 'IMMEDIATE'],
                    [this.customSnippets.items.endorsementTypeCombobox.options.abandonment, 'ABANDONMENT'],
                ],
            }),
        });

        return this.endorsementTypeCombobox;
    },

    /**
     * Creates a checkbox to configure the personal handover service option.
     *
     * @return { Ext.form.field.Checkbox }
     */
    createSignedForByRecipientCheckbox: function () {
        this.signedForByRecipient = Ext.create('Ext.form.field.Checkbox', {
            name: 'signedForByRecipient',
            fieldLabel: this.customSnippets.items.signedForByRecipient.label,
            helpText: this.customSnippets.items.signedForByRecipient.help,
            required: false,
            checked: false,
            labelWidth: 150,
        });

        return this.signedForByRecipient;
    },

    /**
     * Event listener 'onChange' for minimumAge combobox.
     *
     * @param combobox
     */
    onMinimumAgeActive: function (combobox) {
        if (combobox.value !== null) {
            this.identCheckAge.setReadOnly(true);
            this.identCheckAge.addCls('x-item-disabled');
        } else {
            this.identCheckAge.setReadOnly(false);
            this.identCheckAge.removeCls('x-item-disabled');
        }
    },

    /**
     * Event listener 'onChange' for identCheckAge combobox.
     *
     * @param combobox
     */
    onIdentCheckActive: function (combobox) {
        if (combobox.value !== null) {
            this.visualAgeCheck.setReadOnly(true);
            this.visualAgeCheck.addCls('x-item-disabled');
        } else {
            this.visualAgeCheck.setReadOnly(false);
            this.visualAgeCheck.removeCls('x-item-disabled');
        }
    },
});
