// 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 panel of the LabelConfirmWindow containing all form fields, which hold the shipping details
 * and settings of this record(order). Furthermore two buttons (cancel, confirm) are added.
 */
//{namespace name="backend/viison_ups_order/order"}
Ext.define('Shopware.apps.ViisonUPSOrder.view.detail.LabelConfirm', {

    /**
     * Extend from the ShippingCommon LabelConfirm window.
     */
    extend: 'Shopware.apps.ViisonShippingCommonOrder.view.detail.LabelConfirm',

    /**
     * List of short aliases for class names. Most useful for defining xtypes for widgets.
     */
    alias: 'widget.order-viison-ups-label-confirm-panel',

    /**
     * An optional extra CSS class that will be added to this component's Element.
     */
    cls: Ext.baseCSSPrefix + 'order-viison-ups-label-confirm-panel',

    /**
     * The plugin specific prefix used for the custom order record entries
     */
    dispatchServiceProviderPrefix: 'ViisonUPS',
    dispatchServiceProviderName: 'UPS',

    /**
     * More plugin-specific properties required by the parent class
     */
    maxLength: null,

    /**
     * Contains all snippets for the view component.
     */
    customSnippets: {
        details: {
            labels: {
                residentialAddress: '{s name="label_confirm/details/labels/residential_address"}{/s}'
            }
        },
        settingsDetails: {
            labels: {
                additionalHandlingRequired: '{s name="label_confirm/settings_details/labels/additional_handling_required"}{/s}',
                packagingType: '{s name="label_confirm/settings_details/labels/packaging_type"}{/s}',
                product: '{s name="label_confirm/settings_details/labels/product"}{/s}',
                higherInsurance: '{s name="label_confirm/settings_details/labels/higher_insurance"}{/s}',
                insuredValue: '{s name="label_confirm/settings_details/labels/insured_value"}{/s}',
                insuredValueCurrency: '{s name="label_confirm/settings_details/labels/insured_value_currency"}{/s}'
            }
        },
        tooltips: {
            additionalHandlingRequiredHelp: '{s name="label_confirm/tooltips/additional_handling_required_help"}{/s}',
            higherInsuranceHelp: '{s name="label_confirm/tooltips/higher_insurance_help"}{/s}'
        }
    },

    /**
     * @Override
     */
    initComponent: function() {
        var me = this;

        me.packagingTypeStore = Ext.getStore('viison-ups-packaging-type-store').load();

        // Use 'Ext.apply' so if a error by loading the constraints occurs,
        // the object still has the default values
        me.maxLength = Ext.apply({}, me.dimensionConstraints || {}, {
            firstName: undefined,
            lastName: undefined,
            companyName: undefined,
            companyDepartment: undefined,
            street: undefined,
            streetName: undefined,
            streetNumber: undefined,
            zip: undefined,
            city: undefined,
            phoneNumber: undefined,
            email: undefined,
            weight: undefined,
            length: undefined,
            width: undefined,
            height: undefined
        });

        this.callParent(arguments);
    },

    /**
     * Returns the items that this panel consists of.
     */
    getItems: function() {
        var me = this;
        var items;

        if (!me.isReturn) {
            // Forward label
            items = [
                me.createDetailsContainer(),
                me.createPackagingContainer(),
                me.createSettingsDetails()
            ].concat(me.createExtraContainers());
        } else {
            // Return label
            items = [
                me.createDetailsContainer()
            ];
            // Make the weight configurable for free form labels
            if (!me.record) {
                items.push(me.createPackagingContainer());
            } else {
                // show only the weight in 'order'
                items.push(me.createWeightFieldForReturnLabelContainer());
            }
        }

        return items;
    },

    createDetailsFormRows: function(labelWidth, columnPadding) {
        var me = this;
        var details = me.callParent(arguments);
        if (!me.isReturn) {
            details = details.concat([
                {
                    xtype: 'checkbox',
                    name: 'residentialAddress',
                    fieldLabel: me.customSnippets.details.labels.residentialAddress,
                    value: false,
                    uncheckedValue: false,
                    inputValue: true
                }
            ]);
        }
        return details;
    },

    /**
     * Creates all label type form rows containing a label and at least one input field.
     *
     * @param labelWidth The width for all labels in this panel.
     * @param columnPadding
     * @return An array containing the created rows.
     */
    createSettingsFormRows: function(labelWidth, columnPadding) {
        var me = this;

        me.packagingTypeComboBox = {
            xtype: 'combobox',
            flex: 2.5,
            name: 'packagingType',
            fieldLabel: me.customSnippets.settingsDetails.labels.packagingType,
            valueField: 'id',
            displayField: 'name',
            queryMode: 'local',
            mode: 'local',
            required: true,
            editable: false,
            allowBlank: false,
            store: me.packagingTypeStore
        };

        me.additionalHandlingRequired = Ext.create('Ext.form.field.Checkbox', {
            xtype: 'checkbox',
            name: 'additionalHandlingRequired',
            helpText: me.customSnippets.tooltips.additionalHandlingRequiredHelp,
            fieldLabel: me.customSnippets.settingsDetails.labels.additionalHandlingRequired,
            value: false,
            uncheckedValue: false,
            inputValue: true
        });

        me.higherInsurance = Ext.create('Ext.form.field.Checkbox', {
            xtype: 'checkbox',
            name: 'higherInsurance',
            value: false,
            uncheckedValue: false,
            inputValue: true,
            listeners: {
                change: me.higherInsuranceFieldChanged,
                scope: me
            }
        });

        me.insuredValue = Ext.create('Ext.form.field.Number', {
            decimalPrecision: 2,
            submitLocaleSeparator: false,
            name: 'insuredValue',
            fieldLabel: me.customSnippets.settingsDetails.labels.insuredValue,
            labelWidth: 60,
            width: 165,
            allowBlank: false,
            disabled: true
        });

        me.insuredValueCurrency = Ext.create('Ext.form.field.Text', {
            xtype: 'textfield',
            name: 'insuredValueCurrency',
            fieldLabel: me.customSnippets.settingsDetails.labels.insuredValueCurrency,
            helpText: me.customSnippets.tooltips.higherInsuranceHelp,
            labelWidth: 65,
            width: 150,
            value: 'EUR',
            allowBlank: false,
            disabled: true
        });

        return [
            me.createFormRow({
                rowCls: 'confirm-panel-row-product',
                padding: columnPadding,
                label: {
                    width: labelWidth,
                    text: me.customSnippets.settingsDetails.labels.product
                },
                items: [
                    me.productComboBox,
                    me.productIcon,
                    me.packagingTypeComboBox
                ]
            }),
            me.createFormRow({
                rowCls: 'confirm-panel-row-number-of-labels',
                padding: columnPadding,
                label: {
                    width: labelWidth,
                    text: me.snippets.settingsDetails.labels.numberOfLabels,
                    labelStyle: 'margin-top: 0px'
                },
                items: [
                    me.numberOfLabels,
                    me.numberOfLabelsIcon,
                    Ext.create('Ext.form.field.Display', {
                        name: '&nbsp;',
                        flex: 1
                    }),
                    me.cashOnDelivery,
                    me.additionalHandlingRequired
                ]
            }),
            me.createFormRow({
                rowCls: 'confirm-panel-row-higher-insurance',
                padding: columnPadding,
                label: {
                    width: labelWidth,
                    text: me.customSnippets.settingsDetails.labels.higherInsurance,
                    labelStyle: 'margin-top: 0px'
                },
                items: [
                    me.higherInsurance,
                    Ext.create('Ext.form.field.Display', {
                        name: '&nbsp;',
                        flex: 1
                    }),
                    me.insuredValue,
                    Ext.create('Ext.form.field.Display', {
                        name: '&nbsp;',
                        flex: 1
                    }),
                    me.insuredValueCurrency
                ]
            }),
            me.createFormRow({
                rowCls: 'confirm-panel-row-higher-insurance',
                padding: columnPadding,
                items: [
                    me.saturdayDeliveryCheckBox
                ]
            })
        ];
    },

    /**
     * ===============================================
     * Section:: Event & Handlers
     * ===============================================
     */

    /**
     * @Override
     * Update field constraints when the product was changed using the combobox.
     *
     * @param field The field firing the 'change' event.
     * @param newValue The new value of the changed field.
     */
    productChanged: function(field, newValue) {
        var me = this;
        var expressProductCode = 4;

        me.callParent(arguments);
        me.toggleHelper([me.saturdayDeliveryCheckBox], newValue !== expressProductCode);
    },

    /**
     * Called when the higher insurance checkbox gets checked or unchecked.
     *
     * @param field The field firing the 'change' event.
     * @param newValue The new value of the changed field.
     */
    higherInsuranceFieldChanged: function(field, newValue) {
        var me = this;
        me.insuredValue.setDisabled(!newValue);
        me.insuredValueCurrency.setDisabled(!newValue);
    },

    /**
     * @Override
     * Creates checkbox for Saturday delivery option
     *
     * @returns checkbox
     */
    createSaturdayDeliveryCheckBox: function () {
        var me = this;

        var checkBox = me.callParent(arguments);
        checkBox.hidden = true;

        return checkBox;

    },

    /**
     * @override
     */
    setValues: function() {
        var me = this;
        me.callParent(arguments);
        if (me.record && !me.isReturn) {
            me.detailsContainer.getForm().setValues({
                residentialAddress: me.record[me.dispatchServiceProviderPrefix].residentialAddress
            });
            me.additionalHandlingRequired.setValue(me.record[me.dispatchServiceProviderPrefix].additionalHandlingRequired);
            var higherInsurance = me.record[me.dispatchServiceProviderPrefix].higherInsurance;
            me.higherInsurance.setValue(higherInsurance);
            me.insuredValue.setDisabled(!higherInsurance);
            me.insuredValue.setValue(me.record.get('invoiceAmount'));
            me.insuredValueCurrency.setDisabled(!higherInsurance);
            me.insuredValueCurrency.setValue(me.record.get('currency'));
        }
        if (me.settingsContainer) {
            me.settingsContainer.getForm().setValues({
                packagingType: me.getDefaultPackagingType()
            });
        }
    },

    getDefaultPackagingType: function() {
        var me = this;
        if (me.record) {
            return me.record[me.dispatchServiceProviderPrefix].packagingType;
        } else {
            return me.defaultPackagingType;
        }
    },

    /**
     * Dimension constraints used inside the order view
     *
     * Defined: The '$dimensionConstraints' is coming from viewParams() inside backend order Controller
     *
     * Note: The dimensionConstraints are defined at the end of the class because syntax's highlighting is seeing this
     *       as a JS error and so all the editor file is red
     */
     dimensionConstraints: {$dimensionConstraints|@json_encode} || [],

});
