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

Ext.define('Shopware.apps.ViisonPickwareMobileOrderStatusBasedPositionUpdate.controller.List', {

    override: 'Shopware.apps.Order.controller.List',

    /**
     * Gets called when a order is saved on the order list.
     *
     * Checks whether the order status was changed to "Partially delivered" or "Completely delivered" and has positions
     * with pickedQuantities. If so, it shows a hint to the user that informs him, that these items are going to be
     * marked as shipped.
     *
     * @param {Ext.grid.plugin.RowEditing} editor
     * @param {object} event
     * @param {Shopware.apps.Order.store.Order} store
     */
    onSaveOrder: function (editor, event, store) {
        var order = event.record;
        var totalPickedQuantity = ViisonPickwarePickedQuantities.getTotalOfOrder(order);
        var oldStatus = event.originalValues.status;
        var newStatus = event.newValues.status;
        var statusCompletelyDelivered = 7;
        var statusPartiallyDelivered = 6;
        var statusCancelledRejected = 4;
        var statusOpen = 0;

        if (totalPickedQuantity === 0 || oldStatus === newStatus) {
            this.callParent(arguments);

            return;
        }

        // this.callParent() cannot be called asynchronous (in the callback of the MsgBox), therefore we save the
        // super method in a local variable an call that in the callback instead.
        // Determine the superMethod like ExtJS does
        var getCurrentFunction = function () {
            return getCurrentFunction.caller;
        };
        var method = getCurrentFunction();
        var superMethod = method.$previous || (
            (method = method.$owner ? method : method.caller) && method.$owner.superclass[method.$name]
        );

        if (newStatus === statusPartiallyDelivered || newStatus === statusCompletelyDelivered) {
            var countOfPositionsWithPickedQuantities = this.getCountOfPositionsWithPickedQuantites(order);
            Ext.Msg.show({
                title: ViisonCommonApp.getSnippet('dialog/title', 'backend/viison_pickware_mobile_order_status_based_position_update/main'),
                msg: Ext.String.format(
                    ViisonCommonApp.getSnippet('dialog/message', 'backend/viison_pickware_mobile_order_status_based_position_update/main'),
                    countOfPositionsWithPickedQuantities.toString()
                ),
                icon: Ext.Msg.QUESTION,
                buttons: Ext.Msg.OKCANCEL,
                scope: this,
                callback: function (buttonId) {
                    if (buttonId === 'cancel') {
                        event.record.set('status', event.originalValues.status);
                        this.viisonClearProxyParams(order);

                        return;
                    }

                    superMethod.apply(this, [editor, event, store]);
                },
            });
        } else if (newStatus === statusCancelledRejected || newStatus === statusOpen) {
            ViisonPickwareBatchLocationAlertMessage.show({
                scope: this,
                msg: Ext.String.format(
                    ViisonCommonApp.getSnippet('dialog/choose_bin_location/single/message', 'backend/viison_pickware_mobile_order_status_based_position_update/main'),
                    order.get('number')
                ),
                callback: function (buttonId) {
                    if (buttonId === 'cancel') {
                        event.record.set('status', event.originalValues.status);
                        this.viisonClearProxyParams(order);

                        return;
                    }

                    if (buttonId === 'yes') {
                        order.getProxy().extraParams.pickwareMoveStockToOriginalLocation = 1;
                    } else {
                        order.getProxy().extraParams.pickwareMoveStockToOriginalLocation = 0;
                    }

                    superMethod.apply(this, [editor, event, store]);
                },
            });

            return;
        }

        this.callParent(arguments);
    },

    /**
     * @param {Shopware.apps.Order.model.Order} order
     * @returns {Number}
     */
    getCountOfPositionsWithPickedQuantites: function (order) {
        return order.getPositions().getRange().filter(function (position) {
            return position.get('pickwarePickedQuantity') > 0;
        }).length;
    },

    /**
     * To make sure that the property is not saved (no side-effect) after the alert is closed.
     *
     * @Override
     */
    viisonClearProxyParams: function (order) {
        this.callParent(arguments);

        delete order.getProxy().extraParams.pickwareMoveStockToOriginalLocation;
    },

});
