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

/**
 * This controller implements the application logic of the DHL tab that
 * is part of the order detail window. It also handles the event that
 * is fired when clicking the 'Add label' icon in the order list view to
 * directly access the DHL tab.
 */
// {namespace name="backend/viison_dhl_order/order"}
Ext.define('Shopware.apps.ViisonDHLOrder.controller.ShippingLabels', {

    /**
     * Override the ShippingLabels controller from the ShippingCommon module
     */
    override: 'Shopware.apps.ViisonShippingCommonOrder.controller.ShippingLabels',

    dhlCustomSnippets: {
        notifications: {
            growlMessage: '{s name="detail/notifications/growlMessage"}{/s}',
            createLabelNonCodeableError: {
                buttonTitle: '{s name="detail/notifications/createLabelNonCodeableError/buttonTitle"}{/s}',
                message: '{s name="detail/notifications/createLabelNonCodeableError/message"}{/s}',
            },
        },
    },

    init: function () {
        var me = this;

        me.callParent(arguments);

        me.control('order-viison-shipping-common-label-confirm-window', {
            close: me.onLabelConfirmWindowClosed,
        });
    },

    onCreateShippingLabel: function () {
        this.closeNonCodeableNotificationIfActive();
        this.callParent(arguments);
    },

    onDestroyLabelConfirmWindow: function () {
        this.onLabelConfirmWindowClosed();
        this.callParent(arguments);
    },

    onLabelConfirmWindowClosed: function () {
        this.closeNonCodeableNotificationIfActive();
    },

    /**
     * Closes the non-codeable notification if it is active.
     */
    closeNonCodeableNotificationIfActive: function () {
        var me = this;
        if (me.nonCodeableGrowlMessage) {
            Shopware.Notification.closeGrowlMessage(me.nonCodeableGrowlMessage, Shopware.Notification);
            me.nonCodeableGrowlMessage = null;
        }
    },

    afterLabelCreationFinished: function () {
        var me = this;

        if (me.nonCodeableError) {
            var notification = me.snippets.notifications.createLabelError;

            // Show a sticky error notification allowing the user to force the label creation
            me.nonCodeableGrowlMessage = Shopware.Notification.createStickyGrowlMessage({
                title: notification.title,
                text: (me.nonCodeableErrorMessage || '') + '{s name="detail/notifications/createLabelNonCodeableError/message"}{/s}',
                width: 470,
                btnDetail: {
                    text: me.dhlCustomSnippets.notifications.createLabelNonCodeableError.buttonTitle,
                    scope: me,
                    link: '-',
                },
            });
            // Replace the default handler of the custom button to just perform a callback
            me.nonCodeableGrowlMessage.getComponent(1).getComponent(0).setHandler(function () {
                // Force the creation of the label
                me.getLabelConfirmPanel().createLabels({
                    ignorePrintOnlyIfCodeablePreset: true,
                });
            });
            me.nonCodeableGrowlMessage.getComponent(1).getComponent(1).setHandler(function () {
                Shopware.Notification.closeGrowlMessage(me.nonCodeableGrowlMessage, Shopware.Notification);
                me.nonCodeableGrowlMessage = null;
            });

            me.nonCodeableError = false;
        }

        me.callParent(arguments);
    },

    handleLabelCreationError: function (message, errorCode) {
        // Check if an DHL label is about to be created, since this overridden method is also called for other dispatch
        // service providers. Call original function if a label of another dispatch service provider is to be created.
        if (this.dispatchServiceProviderPrefix !== 'ViisonDHL') {
            this.callParent(arguments);

            return;
        }

        // Show error description
        var notification = this.snippets.notifications.createLabelError;
        message = (message && message.length > 0) ? message : notification.message;

        if (errorCode === this.errorCodeNonCodeable) {
            // Save the error to show a sticky growl notification after all requests have finished
            this.nonCodeableError = true;
            this.nonCodeableErrorMessage = message;
        } else {
            Shopware.Notification.createGrowlMessage(notification.title, message, this.dhlCustomSnippets.notifications.growlMessage);
        }
    },

    /**
     * Add the personal handover setting to the shipping label parameters.
     *
     * @override
     * @param details
     * @param packagingDetails
     * @param settings
     */
    getShippingLabelParams: function (record, details, packagingDetails, settings) {
        var params = this.callParent(arguments);
        if (settings) {
            params.settingsMinimumAge = settings.minimumAge;
            params.settingsPersonalHandover = settings.personalHandover;
            params.settingsSaturdayDelivery = settings.saturdayDelivery;
            params.settingsParcelOutletRouting = settings.parcelOutletRouting;
            params.settingsIdentCheckAge = settings.identCheckAge;
            params.settingsPostalDeliveryDutyPaid = settings.postalDeliveryDutyPaid;
            params.settingsClosestDroppointDelivery = settings.closestDroppointDelivery;
            params.settingsSignedForByRecipient = settings.signedForByRecipient;
        }

        return params;
    },

    /**
     * Error code for specific error handling
     *
     * Defined: The '$errorCodeNonCodeable' is coming from viewParams() inside backend order Controller
     *
     * Note: The errorCodeNonCodeable 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
     *
     */
    errorCodeNonCodeable: Ext.JSON.decode('{$errorCodeNonCodeable|@json_encode}') || 1,

});
