// 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.ViisonSetArticlesArticleSetArticlesTab.controller.Main', {

    extend: 'Ext.app.Controller',

    init: function () {
        this.updates = [];

        this.control({
            'article-detail-window': {
                saveArticle: this.onSaveArticle,
            },
            'viison_set_articles_article-view-detail-assignment_panel': {
                updateSetArticle: this.onUpdateSetArticle,
                openArticle: this.onOpenArticle,
                refreshPreview: this.onRefreshPreview,
            },
        });

        this.callParent(arguments);
    },

    /**
     * Is fired when the user clicks on the openArticle button in the actioncolumn.
     * Opens a new article-detail window with the given article(record)
     *
     * @param record
     */
    onOpenArticle: function (record) {
        Shopware.app.Application.addSubApplication({
            name: 'Shopware.apps.Article',
            action: 'detail',
            params: {
                articleId: record.get('articleId'),
            },
        });
    },

    /**
     * Saves update information of one set article in associative array.
     * For each SetId one array of store.data is saved. Therefore is the set article changes again, the data will be
     * overwritten.
     *
     * @param storeData set article composition (store.data)
     * @param id SetId
     */
    onUpdateSetArticle: function (storeData, id) {
        this.updates[id] = storeData;
    },

    /**
     * Saves changes to database.
     * All set articles that have been updated are deleted and saved anew with their current composition.
     */
    onSaveArticle: function () {
        var changelistSetid = [];
        var changelistArticledetailid = [];
        var changelistQuantity = [];
        var deletelistSetid = [];

        this.updates.forEach(function (subArticleConfiguration, setArticleDetailId) {
            if (subArticleConfiguration.length === 0) {
                // Set article is empty, delete only
                deletelistSetid.push(setArticleDetailId);
            } else {
                // Set article not empty, save updates
                subArticleConfiguration.forEach(function (subArticleEntry) {
                    changelistSetid.push(setArticleDetailId);
                    changelistArticledetailid.push(subArticleEntry.data.articleDetailId);
                    changelistQuantity.push(subArticleEntry.data.quantity);
                });
            }
        });

        // Reset (delete configuration) some set articles in batch mode
        if (deletelistSetid.length > 0) {
            var jsonDeleteSetIdArray = Ext.JSON.encode(deletelistSetid);
            Ext.Ajax.request({
                url: ViisonCommonApp.assembleBackendUrl('ViisonSetArticlesArticle/resetSetArticleStack'),
                method: 'POST',
                params: {
                    setIdArray: jsonDeleteSetIdArray,
                },
                scope: this,
            });
        }

        // Update some set articles in batch mode by posting its SetArticleDetailId, SubArticleDetailId and quantity
        if (changelistSetid.length > 0) {
            var jsonSetIdArray = Ext.JSON.encode(changelistSetid);
            var jsonArticleDetailIdArray = Ext.JSON.encode(changelistArticledetailid);
            var jsonQuantityArray = Ext.JSON.encode(changelistQuantity);
            Ext.Ajax.request({
                url: ViisonCommonApp.assembleBackendUrl('ViisonSetArticlesArticle/updateSetArticleStack'),
                method: 'POST',
                params: {
                    setIdArray: jsonSetIdArray,
                    articleDetailIdArray: jsonArticleDetailIdArray,
                    quantityArray: jsonQuantityArray,
                },
                scope: this,
            });
        }

        this.updates = [];
    },

    /**
     * "Refreshes" the current set article combination store to fetch the current availability information which is
     * relevant for the set article availability preview. This refresh function is necessary when a) a sub article is
     * changed (in another article window) and b) the set article combination is not saved yet - so we cannot simply
     * refresh the store, but have to reload the data manually.
     *
     * @param Shopware.apps.ViisonSetArticlesArticleSetArticlesTab.view.detail.AssignmentPanel assignmentPanel
     * @param Shopware.apps.ViisonSetArticlesArticleSetArticlesTab.store.SetArticle store
     * @param int articleDetailId
     */
    onRefreshPreview: function (assignmentPanel, store, articleDetailId) {
        if (store.count() === 0) {
            return;
        }
        assignmentPanel.setArticlePanel.setLoading(true);

        var subArticleDetailIds = Ext.Array.map(store.data.items, function (subArticle) {
            return subArticle.get('articleDetailId');
        }, this);
        var jsonSubArticleDetailIds = Ext.JSON.encode(subArticleDetailIds);
        Ext.Ajax.request({
            url: ViisonCommonApp.assembleBackendUrl('ViisonSetArticlesArticle/getRefreshedSubArticleDetailList'),
            method: 'POST',
            params: {
                jsonSubArticleDetailIds: jsonSubArticleDetailIds,
            },
            scope: this,
            success: function (response) {
                var jsonResponseText = Ext.JSON.decode(response.responseText, true);
                if (jsonResponseText && jsonResponseText.success) {
                    var refreshedArticeDetails = jsonResponseText.data;
                    // Sync the refreshed article detail data with the store data and replace any article fields that
                    // may have been updated.
                    store.data.items.forEach(function (subArticle) {
                        refreshedArticeDetails.forEach(function (refreshedSubArticle) {
                            if (subArticle.get('articleDetailId') === refreshedSubArticle.articleDetailId) {
                                subArticle.set('active', refreshedSubArticle.active);
                                subArticle.set('detailActive', refreshedSubArticle.detailActive);
                                subArticle.set('mainActive', refreshedSubArticle.mainActive);
                                subArticle.set('deliverytime', refreshedSubArticle.deliverytime);
                                subArticle.set('instock', refreshedSubArticle.instock);
                                subArticle.set('maxpurchase', refreshedSubArticle.maxpurchase);
                                subArticle.set('laststock', refreshedSubArticle.laststock);
                                subArticle.set('price', refreshedSubArticle.price);
                                subArticle.set('tax', refreshedSubArticle.laststock);
                                subArticle.set('weight', refreshedSubArticle.weight);
                                subArticle.set('available', ''); // This forces the converted value to be recalculated

                                return false; // break
                            }

                            return true; // continue
                        });
                    });
                }
                assignmentPanel.setArticlePanel.setLoading(false);

                // Send the updates store back to the panel
                assignmentPanel.updateAndOverwriteSetArticleStore(store, articleDetailId);
            },
        });
    },

});
