// 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.ViisonPickwareCommonArticlePropertyTypes.controller.TypeEditor', {

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

    /**
     * @override
     */
    init: function () {
        this.control({
            'viison_pickware_common_article_property_types-type_editor viison_pickware_common_article_property_types-type_editor-type_list': {
                createPropertyType: this.onCreatePropertyType,
                deletePropertyType: this.onDeletePropertyType,
                savePropertyType: this.onSavePropertyType,
            },
            'viison_pickware_common_article_property_types-type_editor-type_creator': {
                save: this.onSaveNewPropertyType,
            },
        });

        this.callParent(arguments);
    },

    /**
     * Creates a new type editor window and makes it visible.
     *
     * @param Function callback
     */
    createEditor: function (callback) {
        var editor = this.getView('Shopware.apps.ViisonPickwareCommonArticlePropertyTypes.view.TypeEditor').create();
        editor.on('close', function () {
            if (Ext.isFunction(callback)) {
                callback();
            }
        });
        editor.show();
    },

    /**
     * Creates a new type creator window and makes it visible.
     *
     * @param Shopware.apps.ViisonPickwareCommonArticlePropertyTypes.view.typeEditor.TypeList gridPanel
     */
    onCreatePropertyType: function (gridPanel) {
        var creator = this.getView('Shopware.apps.ViisonPickwareCommonArticlePropertyTypes.view.typeEditor.TypeCreator').create({
            propertyTypeStore: gridPanel.store,
        });
        creator.on('close', function () {
            gridPanel.store.load();
        });
        creator.show();
    },

    /**
     * First presents a confirmation alert and, if the user confirms it, removes the given typeRecord from its store
     * and syncs the store's changes.
     *
     * @param Shopware.apps.ViisonPickwareCommonArticlePropertyTypes.view.typeEditor.TypeList gridPanel
     * @param Shopware.apps.ViisonPickwareCommonArticlePropertyTypes.model.PropertyType typeRecord
     */
    onDeletePropertyType: function (gridPanel, typeRecord) {
        // Ask the user for confirmation
        Ext.Msg.confirm(
            this.getViisonSnippet('type_editor/on_delete_property_type/confirmation_alert/title'),
            this.getViisonSnippet('type_editor/on_delete_property_type/confirmation_alert/message'),
            function (buttonId) {
                if (buttonId !== 'yes') {
                    return;
                }

                // Remove record from its store and sync the changes
                gridPanel.store.remove(typeRecord);
                gridPanel.store.sync({
                    scope: this,
                    success: function () {
                        gridPanel.store.loadPage(1);
                        var message = Ext.String.format(
                            this.getViisonSnippet('type_editor/on_delete_property_type/notification/success/message'),
                            typeRecord.get('name')
                        );
                        Shopware.Notification.createGrowlMessage(
                            this.getViisonSnippet('type_editor/on_delete_property_type/notification/success/title'),
                            message,
                            'ViisonPickwareCommon'
                        );
                    },
                    failure: function () {
                        gridPanel.store.rejectChanges();
                        var message = Ext.String.format(
                            this.getViisonSnippet('type_editor/on_delete_property_type/notification/failure/message'),
                            typeRecord.get('name')
                        );
                        Shopware.Notification.createGrowlMessage(
                            this.getViisonSnippet('type_editor/on_delete_property_type/notification/failure/title'),
                            message,
                            'ViisonPickwareCommon'
                        );
                    },
                });
            },
            this
        );
    },

    /**
     * Syncs the changed typeRecord's store.
     *
     * @param Shopware.apps.ViisonPickwareCommonArticlePropertyTypes.view.typeEditor.TypeList gridPanel
     * @param Shopware.apps.ViisonPickwareCommonArticlePropertyTypes.model.PropertyType typeRecord
     */
    onSavePropertyType: function (gridPanel, typeRecord) {
        gridPanel.setLoading(true);
        gridPanel.store.sync({
            scope: this,
            success: function () {
                gridPanel.setLoading(false);
                var message = Ext.String.format(
                    this.getViisonSnippet('type_editor/on_save_property_type/notification/success/message'),
                    typeRecord.get('name')
                );
                Shopware.Notification.createGrowlMessage(
                    this.getViisonSnippet('type_editor/on_save_property_type/notification/success/title'),
                    message,
                    'ViisonPickwareCommon'
                );
            },
            failure: function (batch) {
                gridPanel.setLoading(false);
                gridPanel.store.rejectChanges();
                var errorMessage = batch.exceptions[0].getError();
                var message = Ext.String.format(
                    this.getViisonSnippet('type_editor/on_save_property_type/notification/failure/message'),
                    typeRecord.get('name'),
                    errorMessage
                );
                Shopware.Notification.createGrowlMessage(
                    this.getViisonSnippet('type_editor/on_save_property_type/notification/failure/title'),
                    message,
                    'ViisonPickwareCommon'
                );
            },
        });
    },

    /**
     * Validates the given creationWindow's form and, if it is valid, creates a new PropertyType record using
     * the form values. Finally the record is added to the main store, which is then synced.
     *
     * @param Shopware.apps.ViisonPickwareCommonArticlePropertyTypes.view.typeEditor.TypeCreator creationWindow
     */
    onSaveNewPropertyType: function (creationWindow) {
        // Validate the form
        var panel = creationWindow.down('form');
        if (!panel.getForm().isValid()) {
            return;
        }

        // Create a new property type using the form data
        var formValues = panel.getForm().getValues();
        var propertyType = Ext.create('Shopware.apps.ViisonPickwareCommonArticlePropertyTypes.model.PropertyType', {});
        propertyType.set('name', formValues.name);

        // Add the property type to the store and save it
        creationWindow.setLoading(true);
        creationWindow.propertyTypeStore.add(propertyType);
        creationWindow.propertyTypeStore.sync({
            scope: this,
            success: function () {
                creationWindow.close();
                var message = Ext.String.format(
                    this.getViisonSnippet('type_editor/on_save_new_property_type/notification/success/message'),
                    formValues.name
                );
                Shopware.Notification.createGrowlMessage(
                    this.getViisonSnippet('type_editor/on_save_new_property_type/notification/success/title'),
                    message,
                    'ViisonPickwareCommon'
                );
            },
            failure: function (batch) {
                creationWindow.setLoading(false);
                creationWindow.propertyTypeStore.rejectChanges();
                var errorMessage = batch.exceptions[0].getError();
                var message = Ext.String.format(
                    this.getViisonSnippet('type_editor/on_save_new_property_type/notification/failure/message'),
                    formValues.name,
                    errorMessage
                );
                Shopware.Notification.createGrowlMessage(
                    this.getViisonSnippet('type_editor/on_save_new_property_type/notification/failure/title'),
                    message,
                    'ViisonPickwareCommon'
                );
            },
        });
    },

});
