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

    extend: 'Ext.app.Controller',
    mixins: [
        'Shopware.apps.ViisonCommonApp.Mixin',
    ],
    viisonSnippetNamespace: 'backend/viison_pickware_mobile_pick_profiles/main',

    /**
     * @override
     */
    init: function () {
        this.control({
            'viison_pickware_mobile_pick_profiles-main-list button[action=addPickProfile]': {
                click: this.onAddPickProfile,
            },
            'viison_pickware_mobile_pick_profiles-main-list': {
                editPickProfile: this.onEditPickProfile,
                deletePickProfile: this.onDeletePickProfile,
                duplicatePickProfile: this.onDuplicatePickProfile,
                searchFieldChanged: this.onSearchFieldChanged,
            },
        });

        // Create and load the main pick profile store
        this.pickProfileStore = Ext.create('Shopware.apps.ViisonPickwareMobilePickProfiles.store.PickProfile', {});
        this.pickProfileStore.load();

        // Create the main window
        this.mainView = this.getView('Main').create({
            pickProfileStore: this.pickProfileStore,
        });

        this.callParent(arguments);
    },

    /**
     * Creates an empty pick profile model instance and passes it to a new edit window.
     */
    onAddPickProfile: function () {
        var newPickProfile = Ext.create('Shopware.apps.ViisonPickwareMobilePickProfiles.model.PickProfile', {});
        this.getController('Edit').createEditWindow(newPickProfile);
    },

    /**
     * Opens a new edit window using the given pick profile.
     *
     * @param {Shopware.apps.ViisonPickwareMobilePickProfiles.model.PickProfile} pickProfile
     */
    onEditPickProfile: function (pickProfile) {
        this.getController('Edit').createEditWindow(pickProfile);
    },

    /**
     * Ask the user for confirmation of the deletion and, if confirmed, deletes the given pick profile from the store
     * and syncs the store afterwards.
     *
     * @param {Shopware.apps.ViisonPickwareMobilePickProfiles.model.PickProfile} pickProfile
     */
    onDeletePickProfile: function (pickProfile) {
        // Present a confirm alert before deleting the pick profile
        Ext.Msg.confirm(
            this.getViisonSnippet('alert/title'),
            this.getViisonSnippet('alert/message/delete_pick_profile'),
            function (buttonId) {
                if (buttonId !== 'yes') {
                    return;
                }

                // Remove the given pick profile from the store and sync the changes
                this.pickProfileStore.remove(pickProfile);
                this.syncPickProfiles(this.getViisonSnippet('notification/error/message/delete_pick_profile'));
            },
            this
        );
    },

    /**
     * Creates a new pick profile and copies over all settings of the given `pickProfile`, before saving the store.
     *
     * @param {Shopware.apps.ViisonPickwareMobilePickProfiles.model.PickProfile} pickProfile
     */
    onDuplicatePickProfile: function (pickProfile) {
        // Copy the pick profile, but change id and name
        var newPickProfile = pickProfile.copy();
        Ext.data.Model.id(newPickProfile);
        newPickProfile.set('name', newPickProfile.get('name') + ' (2)');

        // Save the new pick profile in the store
        this.pickProfileStore.add(newPickProfile);
        this.syncPickProfiles(this.getViisonSnippet('notification/error/message/duplicate_pick_profile'));
    },

    /**
     * Sets the given query as an extra parameter to the pick profile store's proxy and reloads the store.
     *
     * @param {String} query
     */
    onSearchFieldChanged: function (query) {
        this.pickProfileStore.getProxy().extraParams.query = query;
        this.pickProfileStore.loadPage(1);
    },

    /**
     * Synchronizes the pick profile store and, in case of failure, shows a growl notification.
     *
     * @param {String} errorMessage
     * @param {function} callback (optional)
     */
    syncPickProfiles: function (errorMessage, callback) {
        // Check the store for any changes
        var numChanges = (
            this.pickProfileStore.getNewRecords().length
            + this.pickProfileStore.getModifiedRecords().length
            + this.pickProfileStore.getUpdatedRecords().length
            + this.pickProfileStore.getRemovedRecords().length
        );
        if (numChanges === 0) {
            if (Ext.isFunction(callback)) {
                callback(true);
            }

            return;
        }

        // Sync the store
        this.selectedRow = null;
        if (this.mainView) {
            this.mainView.setLoading(true);
        }
        this.pickProfileStore.sync({
            scope: this,
            success: function () {
                if (this.mainView) {
                    this.mainView.setLoading(false);
                }

                // Reload the store, because a sync does not udpate all of its state properly
                this.pickProfileStore.loadPage(this.pickProfileStore.currentPage, {
                    scope: this,
                    callback: function () {
                        if (Ext.isFunction(callback)) {
                            callback(true);
                        }
                    },
                });
            },
            failure: function (batch) {
                if (this.mainView) {
                    this.mainView.setLoading(false);
                }
                // Revert any changes like added, updated or removed records
                this.pickProfileStore.rejectChanges();
                // Display an error notification
                var message = errorMessage || '';
                Shopware.Notification.createGrowlMessage(
                    this.getViisonSnippet('notification/error/title'),
                    message,
                    'ViisonPickwareMobilePickProfiles'
                );
                if (Ext.isFunction(callback)) {
                    callback(false, batch.proxy.reader.jsonData);
                }
            },
        });
    },

});
