// 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 UPS configuration form panel, which is displayed in the window that is accessible via the
 * button in the plugin description in the plugin manager.
 */
//{namespace name="backend/viison_ups_config/config"}
Ext.define('Shopware.apps.ViisonUPSConfig.view.Panel', {

    /**
     * Extend the config panel from the ShippingCommon module
     */
    extend: 'Shopware.apps.ViisonShippingCommonConfig.view.Panel',

    xtype: 'viisonupsconfig-panel',

    /**
     * Constant definitions for the GDPR dropdown values.
     */
    GDPR_ALWAYS: '{$viisonGdprConfig.always}',
    GDPR_NEVER: '{$viisonGdprConfig.never}',
    GDPR_CUSTOMER_CHOICE: '{$viisonGdprConfig.customerChoice}',

    /**
     * Contains all snippets for the view component.
     */
    snippets: {
        items: {
            senderName: {
                label: '{s name="panel/items/sender_name/label"}{/s}',
                help: '{s name="panel/items/sender_name/help"}{/s}'
            },
            streetName: {
                label: '{s name="panel/items/street_name/label"}{/s}',
                help: '{s name="panel/items/street_name/help"}{/s}'
            },
            streetNumber: {
                label: '{s name="panel/items/street_number/label"}{/s}',
                help: '{s name="panel/items/street_number/help"}{/s}'
            },
            zipCode: {
                label: '{s name="panel/items/zip_code/label"}{/s}',
                help: '{s name="panel/items/zip_code/help"}{/s}'
            },
            city: {
                label: '{s name="panel/items/city/label"}{/s}',
                help: '{s name="panel/items/city/help"}{/s}'
            },
            country: {
                label: '{s name="panel/items/country/label"}{/s}',
                help: '{s name="panel/items/country/help"}{/s}'
            },
            contactPerson: {
                label: '{s name="panel/items/contact_person/label"}{/s}',
                help: '{s name="panel/items/contact_person/help"}{/s}'
            },
            email: {
                label: '{s name="panel/items/email/label"}{/s}',
                help: '{s name="panel/items/email/help"}{/s}'
            },
            phoneNumber: {
                label: '{s name="panel/items/phone_number/label"}{/s}',
                help: '{s name="panel/items/phone_number/help"}{/s}'
            },
            userId: {
                label: '{s name="panel/items/user_id/label"}{/s}',
                help: '{s name="panel/items/user_id/help"}{/s}'
            },
            password: {
                label: '{s name="panel/items/password/label"}{/s}',
                help: '{s name="panel/items/password/help"}{/s}'
            },
            accessKey: {
                label: '{s name="panel/items/access_key/label"}{/s}',
                help: '{s name="panel/items/access_key/help"}{/s}'
            },
            accountNumber: {
                label: '{s name="panel/items/account_number/label"}{/s}',
                help: '{s name="panel/items/account_number/help"}{/s}'
            },
            negotiatedRates: {
                label: '{s name="panel/items/negotiated_rates/label"}{/s}',
                help: '{s name="panel/items/negotiated_rates/help"}{/s}'
            },
            defaultPackagingType: {
                label: '{s name="panel/items/default_packaging_type/label"}{/s}',
                help: '{s name="panel/items/default_packaging_type/help"}{/s}'
            },
            returnProduct: {
                label: '{s name="panel/items/return_product/label"}{/s}',
                help: '{s name="panel/items/return_product/help"}{/s}'
            },
            pdfSize: {
                label: '{s name="panel/items/pdf_size/label"}{/s}',
                help: '{s name="panel/items/pdf_size/help"}{/s}',
                a4: '{s name="panel/items/pdf_size/a4"}{/s}',
                a5: '{s name="panel/items/pdf_size/a5"}{/s}',
                '4x6-inch': '{s name="panel/items/pdf_size/4x6-inch"}{/s}',
                '4x7-inch': '{s name="panel/items/pdf_size/4x7-inch"}{/s}',
            },
            weightSeparator: {
                label: '{s name="panel/items/weight_separator/label"}{/s}'
            },
            defaultShipmentWeight: {
                label: '{s name="panel/items/default_shipment_weight/label"}{/s}',
                help: '{s name="panel/items/default_shipment_weight/help"}{/s}'
            },
            calculateWeight: {
                label: '{s name="panel/items/calculate_weight/label"}{/s}',
                help: '{s name="panel/items/calculate_weight/help"}{/s}'
            },
            fillerSurcharge: {
                label: '{s name="panel/items/filler_surcharge/label"}{/s}',
                help: '{s name="panel/items/filler_surcharge/help"}{/s}'
            },
            packagingSurcharge: {
                label: '{s name="panel/items/packaging_surcharge/label"}{/s}',
                help: '{s name="panel/items/packaging_surcharge/help"}{/s}'
            },
            notificationEmailSeparator: {
                label: '{s name="panel/items/notification_email_description/label"}{/s}'
            },
            sendDispatchNotification: {
                label: '{s name="panel/items/send_dispatch_notification/label"}{/s}',
                help: '{s name="panel/items/send_dispatch_notification/help"}{/s}'
            },
            dispatchNotificationText: {
                label: '{s name="panel/items/dispatch_notification_text/label"}{/s}',
                help: '{s name="panel/items/dispatch_notification_text/help"}{/s}'
            },
            sendDeliveryNotification: {
                label: '{s name="panel/items/send_delivery_notification/label"}{/s}',
                help: '{s name="panel/items/send_delivery_notification/help"}{/s}'
            },
            gdprMailConfiguration: {
                label: '{s name="panel/items/gdpr_mail_configuration/label"}{/s}',
                help: '{s name="panel/items/gdpr_mail_configuration/help"}{/s}',
                never: '{s name="panel/items/gdpr_mail_configuration/never"}{/s}',
                always: '{s name="panel/items/gdpr_mail_configuration/always"}{/s}',
                customerChoice: '{s name="panel/items/gdpr_mail_configuration/customer_choice"}{/s}',
            },
            gdprPhoneConfiguration: {
                label: '{s name="panel/items/gdpr_phone_configuration/label"}{/s}',
                help: '{s name="panel/items/gdpr_phone_configuration/help"}{/s}',
                never: '{s name="panel/items/gdpr_phone_configuration/never"}{/s}',
                always: '{s name="panel/items/gdpr_phone_configuration/always"}{/s}',
            },
        },
        'groupValidationFailed': '{s name="panel/group_validation_failed"}{/s}',
        'groupDependencyValidationFailed': '{s name="panel/group_dependency_validation_failed"}{/s}',
        'disallowBlankIfCheckedValidationFailed': '{s name="panel/disallow_blank_if_checked_validation_failed"}{/s}'
    },

    /**
     * If groups need to be filled out if another group has entries, this
     * dependency can be expressed here. These dependencies are enforced
     * by the group validator.
     *
     * The current settings mean: the 'base' group needs to be filled out
     * if either the group 'international-shipment' or 'cash-on-delivery' is set
     */
    groupDependencies: {
        base: [
            'international-shipment'
        ]
    },

    initComponent: function() {
        var me = this;

        // Prepare stores
        me.packagingTypeStore = Ext.create('Shopware.apps.ViisonUPSShipping.store.PackagingType').load(function() {
            if (me.packagingTypeStore.find('id', 0) === -1) {
                // Add 'none' product
                me.packagingTypeStore.add({
                    id: null,
                    name: '-',
                    code: ''
                });
            }
        });

        me.productStore = Ext.create('Shopware.apps.ViisonUPSShipping.store.Product').load();
        me.countriesStore = Ext.create('Shopware.apps.ViisonShippingCommonFreeFormLabels.store.Country').load();

        me.callParent(arguments);

        /** @Override from ShippingCommon */
        if (me.sharedConfigFields && me.sharedConfigFields.cashOnDeliveryPaymentMeansSection) {
            me.sharedConfigFields.cashOnDeliveryPaymentMeansSection.activate = true;
        }

    },

    /**
     * @inheritDoc
     */
    initForm: function () {
        this.callParent(arguments);
    },

    /**
     * Creates and returns an array of all input fields belonging to this configuration form.
     *
     * @return An array containing all created input fields.
     */
    createItems: function(shop) {
        var me = this;

        var items = [{
            xtype: 'base-element-text',
            name: 'senderName',
            fieldLabel: me.snippets.items.senderName.label,
            helpText: me.snippets.items.senderName.help,
            maxLength: 30,
            group: 'base',
            validator: me.groupValidator
        }, {
            xtype: 'base-element-text',
            name: 'streetName',
            fieldLabel: me.snippets.items.streetName.label,
            helpText: me.snippets.items.streetName.help,
            maxLength: 30,
            group: 'base',
            validator: me.groupValidator
        }, {
            xtype: 'base-element-text',
            name: 'streetNumber',
            fieldLabel: me.snippets.items.streetNumber.label,
            helpText: me.snippets.items.streetNumber.help,
            maxLength: 30,
            group: 'base',
            validator: me.groupValidator
        }, {
            xtype: 'base-element-text',
            name: 'zipCode',
            fieldLabel: me.snippets.items.zipCode.label,
            helpText: me.snippets.items.zipCode.help,
            maxLength: 30,
            group: 'base',
            validator: me.groupValidator,
            maskRe: /[\d]/
        }, {
            xtype: 'base-element-text',
            name: 'city',
            fieldLabel: me.snippets.items.city.label,
            helpText: me.snippets.items.city.help,
            maxLength: 30,
            group: 'base',
            validator: me.groupValidator
        }, {
            xtype: 'combobox',
            name: 'countryId',
            fieldLabel: me.snippets.items.country.label,
            helpText: me.snippets.items.country.help,
            valueField: 'id',
            displayField: 'name',
            queryMode: 'local',
            mode: 'local',
            editable: false,
            store: me.countriesStore,
            group: 'base',
            validator: me.groupValidator
        }, {
            xtype: 'base-element-text',
            name: 'contactPerson',
            fieldLabel: me.snippets.items.contactPerson.label,
            helpText: me.snippets.items.contactPerson.help,
            maxLength: 30,
            group: 'base',
            validator: me.groupValidator
        }, {
            xtype: 'base-element-text',
            name: 'email',
            fieldLabel: me.snippets.items.email.label,
            helpText: me.snippets.items.email.help,
            maxLength: 50,
            vtype: 'email',
            group: 'base',
            validator: me.groupValidator
        }, {
            xtype: 'base-element-text',
            name: 'phoneNumber',
            fieldLabel: me.snippets.items.phoneNumber.label,
            helpText: me.snippets.items.phoneNumber.help,
            maxLength: 30,
            group: 'base',
            validator: me.groupValidator,
            maskRe: /[\d\+]/
        }, {
            xtype: 'base-element-text',
            name: 'userId',
            fieldLabel: me.snippets.items.userId.label,
            helpText: me.snippets.items.userId.help,
            maxLength: 255,
            group: 'base',
            validator: me.groupValidator
        }, {
            xtype: 'base-element-text',
            name: 'password',
            fieldLabel: me.snippets.items.password.label,
            helpText: me.snippets.items.password.help,
            maxLength: 255,
            inputType: 'password',
            group: 'base',
            validator: me.groupValidator
        }, {
            xtype: 'base-element-text',
            name: 'accessKey',
            fieldLabel: me.snippets.items.accessKey.label,
            helpText: me.snippets.items.accessKey.help,
            group: 'base',
            validator: me.groupValidator
        }, {
            xtype: 'base-element-text',
            name: 'accountNumber',
            fieldLabel: me.snippets.items.accountNumber.label,
            helpText: me.snippets.items.accountNumber.help,
            group: 'base',
            validator: me.groupValidator
        }, {
            xtype: 'base-element-boolean',
            name: 'useTestingWebservice',
            fieldLabel: '{s name="panel/items/use_testing_webservice/label"}{/s}',
            helpText: '{s name="panel/items/use_testing_webservice/help"}{/s}',
            checked: false
        }, {
            xtype: 'base-element-boolean',
            name: 'negotiatedRates',
            fieldLabel: me.snippets.items.negotiatedRates.label,
            helpText: me.snippets.items.negotiatedRates.help,
            checked: false
        }, {
            xtype: 'combobox',
            name: 'defaultPackagingType',
            fieldLabel: me.snippets.items.defaultPackagingType.label,
            helpText: me.snippets.items.defaultPackagingType.help,
            valueField: 'id',
            displayField: 'name',
            queryMode: 'local',
            mode: 'local',
            editable: false,
            emptyText: '-',
            store: me.packagingTypeStore
        }, {
            xtype: 'combobox',
            name: 'returnProduct',
            fieldLabel: me.snippets.items.returnProduct.label,
            helpText: me.snippets.items.returnProduct.help,
            valueField: 'id',
            displayField: 'name',
            queryMode: 'local',
            mode: 'local',
            editable: false,
            store: me.productStore

        }, {
            xtype: 'combobox',
            name: 'pdfSize',
            fieldLabel: me.snippets.items.pdfSize.label,
            helpText: me.snippets.items.pdfSize.help,
            valueField: 'value',
            displayField: 'displayName',
            queryMode: 'local',
            mode: 'local',
            editable: false,
            store: Ext.create('Ext.data.Store', {
                fields: [
                    { name: 'value', type: 'string' },
                    { name: 'displayName', type: 'string' },
                ],
                data: [
                    { value: 'A4', displayName: me.snippets.items.pdfSize.a4},
                    { value: 'A5', displayName: me.snippets.items.pdfSize.a5},
                    { value: '4x6-inch', displayName: me.snippets.items.pdfSize['4x6-inch']},
                    { value: '4x7-inch', displayName: me.snippets.items.pdfSize['4x7-inch']},
                ]
            })
        }, {
            xtype: 'container',
            margin: '15 0 10 0',
            items: [{
                xtype: 'label',
                text: me.snippets.items.weightSeparator.label
            }]
        }, {
            xtype: 'x-custom-field-weight',
            name: 'defaultShipmentWeight',
            fieldLabel: me.snippets.items.defaultShipmentWeight.label,
            helpText: me.snippets.items.defaultShipmentWeight.help,
            defaultSubmitValue: 0,
            allowBlank: false
        }, {
            xtype: 'base-element-boolean',
            name: 'calculateWeight',
            fieldLabel: me.snippets.items.calculateWeight.label,
            helpText: me.snippets.items.calculateWeight.help,
            checked: false
        }, {
            xtype: 'x-custom-field-weight',
            name: 'fillerSurcharge',
            fieldLabel: me.snippets.items.fillerSurcharge.label,
            helpText: me.snippets.items.fillerSurcharge.help,
            defaultSubmitValue: 0,
            allowBlank: false
        }, {
            xtype: 'x-custom-field-weight',
            name: 'packagingSurcharge',
            fieldLabel: me.snippets.items.packagingSurcharge.label,
            helpText: me.snippets.items.packagingSurcharge.help,
            defaultSubmitValue: 0,
            allowBlank: false
        }, {
            xtype: 'container',
            margin: '15 0 10 0',
            items: [{
                xtype: 'label',
                text: me.snippets.items.notificationEmailSeparator.label
            }]
        }, {
            xtype: 'combobox',
            name: 'gdprPhoneConfiguration',
            fieldLabel: this.snippets.items.gdprPhoneConfiguration.label,
            helpText: this.snippets.items.gdprPhoneConfiguration.help,
            valueField: 'value',
            displayField: 'displayName',
            queryMode: 'local',
            mode: 'local',
            editable: false,
            store: Ext.create('Ext.data.Store', {
                fields: [
                    { name: 'value', type: 'string' },
                    { name: 'displayName', type: 'string' },
                ],
                data: [
                    { value: this.GDPR_NEVER, displayName: this.snippets.items.gdprPhoneConfiguration.never },
                    { value: this.GDPR_ALWAYS, displayName: this.snippets.items.gdprPhoneConfiguration.always },
                ],
            }),
        }, {
            xtype: 'combobox',
            name: 'gdprMailConfiguration',
            fieldLabel: this.snippets.items.gdprMailConfiguration.label,
            helpText: this.snippets.items.gdprMailConfiguration.help,
            valueField: 'value',
            displayField: 'displayName',
            queryMode: 'local',
            mode: 'local',
            editable: false,
            store: Ext.create('Ext.data.Store', {
                fields: [
                    { name: 'value', type: 'string' },
                    { name: 'displayName', type: 'string' },
                ],
                data: [
                    { value: this.GDPR_NEVER, displayName: this.snippets.items.gdprMailConfiguration.never },
                    { value: this.GDPR_ALWAYS, displayName: this.snippets.items.gdprMailConfiguration.always },
                    { value: this.GDPR_CUSTOMER_CHOICE, displayName: this.snippets.items.gdprMailConfiguration.customerChoice },
                ]
            }),
            listeners: {
                change: this.onCustomerDataTransmittingAllowedChange,
                scope: this,
            },
        }, {
            xtype: 'base-element-boolean',
            name: 'sendDispatchNotification',
            fieldLabel: me.snippets.items.sendDispatchNotification.label,
            helpText: me.snippets.items.sendDispatchNotification.help,
            checked: false
        }, {
            xtype: 'base-element-textarea',
            name: 'dispatchNotificationText',
            fieldLabel: me.snippets.items.dispatchNotificationText.label,
            helpText: me.snippets.items.dispatchNotificationText.help,
            allowBlank: true
        }, {
            xtype: 'base-element-boolean',
            name: 'sendDeliveryNotification',
            fieldLabel: me.snippets.items.sendDeliveryNotification.label,
            helpText: me.snippets.items.sendDeliveryNotification.help,
            checked: false
        }];

        return items;
    },

    /**
     * Trigger the update of the dispatch and delivery notification checkbox disabled state if no customer data
     * is allowed to be transmitted.
     *
     * @param field
     * @param newValue
     */
    onCustomerDataTransmittingAllowedChange: function (field, newValue) {
        this.updateDispatchAndDeliveryContainerVisibility(field.shopId, newValue === this.GDPR_NEVER);
    },

    /**
     * Disable/Enable the dispatch and delivery notification checkbox.
     *
     * @param disabled
     */
    updateDispatchAndDeliveryContainerVisibility: function (shopId, disabled) {
        var form = this.getForm();
        var sendDispatchNotificationContainer = form.findField(this.makeShopQualifiedFieldName(shopId, 'sendDispatchNotification'));
        var sendDeliveryNotificationContainer = form.findField(this.makeShopQualifiedFieldName(shopId, 'sendDeliveryNotification'));
        var dispatchNotificationTextContainer = form.findField(this.makeShopQualifiedFieldName(shopId, 'dispatchNotificationText'));
        sendDispatchNotificationContainer.setDisabled(disabled);
        sendDeliveryNotificationContainer.setDisabled(disabled);
        dispatchNotificationTextContainer.setDisabled(disabled);
    },

});
