// 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 implementation of the order overview list adds a fourth button/icon to each order row,
 * which opens the order details, focuses the dispatch service provider tab and opens a LabelConfirmWindow.
 * Furthermore a new batch processing button is added to the upper toolbar to create the shipping labels
 * of multiple orders at once.
 */
//{namespace name="backend/viison_shipping_common_order/order"}
Ext.define('Shopware.apps.ViisonShippingCommonOrder.view.list.List', {

    override: 'Shopware.apps.Order.view.list.List',

    /**
     * Contains all snippets for the view component.
     */
    viisonShippingCommon: {
        snippets: {
            buttons: {
                batchLabelCreation: '{s name="list/buttons/batch_label_creation"}{/s}'
            },
            tooltips: {
                addLabel: '{s name="list/tooltips/add_label"}{/s}',
                showTracking: '{s name="list/tooltips/show_tracking"}{/s}'
            }
        },
        hasDispatchServiceProvider: false
    },

    viisonExtraBatchButtons: [],

    initComponent: function() {
        var me = this;

        me.viisonAddBatchButton(Ext.create('Ext.button.Button', {
            iconCls: 'c-sprite-box--plus',
            text: me.viisonShippingCommon.snippets.buttons.batchLabelCreation,
            action: 'viisonBatchLabelCreation',
            disabled: true,
            handler: function () {
                me.fireEvent('viisonBatchLabelCreation', me);
            }
        }));

        me.callParent(arguments);
    },

    /**
     * Override the default 'getColumns' method to add shipping buttons to the action column.
     */
    getColumns: function() {
        var columns = this.callParent(arguments),
            actionColumnIndex = -1,
            actionColumn;

        // Find index of last actionColumn in columns array
        Ext.Array.each(columns, function(item, index) {
            if (Ext.getClassName(item) == 'Ext.grid.column.Action') {
                actionColumnIndex = index;
            }
        });

        // Add buttons, if an actionColumn was found
        if (actionColumnIndex > -1) {
            actionColumn = columns[actionColumnIndex];

            // Add buttons
            actionColumn.items.push(this.createAddLabelButton());
            actionColumn.items.push(this.createTrackingButton());

            // "Reinitialize" action column
            columns[actionColumnIndex] = Ext.create('Ext.grid.column.Action', {
                width: actionColumn.width + 45,
                items: actionColumn.items
            });

            // Destroy old action column
            actionColumn.destroy();
        }

        return columns;
    },

    /**
     * Creates a new button containing a 'box plus' icon. Clicking this button
     * fires the 'showDetailDispatchServiceProviderTab' event.
     *
     * @return The created 'add' button.
     */
    createAddLabelButton: function() {
        var me = this;

        return {
            iconCls: 'c-sprite-box--plus',
            action: 'viisonShowDetailDispatchServiceProviderTab',
            tooltip: me.viisonShippingCommon.snippets.tooltips.addLabel,
            handler: function(view, rowIndex, colIndex, item) {
                var store = view.getStore();
                var record = store.getAt(rowIndex);
                me.fireEvent('viisonShowDetailDispatchServiceProviderTab', record, view);
            },
            getClass: function(html, metadata, record) {
                // Hide this action icon, if the order doesn't have a DHL shipping method
                if (!record.raw.hasDispatchMethod) {
                    return 'x-hide-display';
                }
            }
        };
    },

    /**
     * Creates a new button containing a 'box search' icon. Clicking this button
     * fires the 'trackShipments' event.
     *
     * @return The created 'tracking' button.
     */
    createTrackingButton: function() {
        var me = this;

        return {
            iconCls: 'c-sprite-box-search-result',
            action: 'viisonTrackShipments',
            tooltip: me.viisonShippingCommon.snippets.tooltips.showTracking,
            handler: function(view, rowIndex, colIndex, item) {
                var store = view.getStore();
                var record = store.getAt(rowIndex);
                me.fireEvent('viisonTrackShipments', record);
            },
            getClass: function(html, metadata, record) {
                // Hide this action icon, if the order doesn't have a DHL shipping method
                if (!record.raw.hasDispatchMethod) {
                    return 'x-hide-display';
                }
            }
        };
    },

    /**
     * By overriding this function, not only the default batch button's state is
     * toggled, but also the state custom shipping label batch buttons.
     *
     * @return The create checkbox model.
     */
    getGridSelModel: function() {
        var me = this;
        var model = me.callParent(arguments);

        model.addListener('selectionchange', function(selectionModel, selections) {
            // Unlock batch buttons, if the user has checked at least one checkbox
            Ext.each(me.viisonExtraBatchButtons, function(button) {
                if (button !== null) {
                    button.setDisabled(selections.length === 0);
                }
            });
        });

        return model;
    },

    viisonAddBatchButton: function(button) {
        var me = this;
        me.viisonExtraBatchButtons = (me.viisonExtraBatchButtons || []).concat(button);
    },

    /**
     * By overriding this function, additional batch buttons are added to the toolbar
     * (e.g. for batch creation of shipping labels).
     *
     * @return The created toolbar containing the additional buttons.
     */
    getToolbar: function() {
        var me = this;

        // Create toolbar by calling the parent function and add the button
        var toolbar = me.callParent(arguments);
        Ext.each(me.viisonExtraBatchButtons, function(button) {
            toolbar.insert(1, button);
        });

        return toolbar;
    }
});
