/*
 *  Copyright 2017 Anyware Services
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * This UI helper provides a dialog to select one or more orgunits on a orgunits tree.
 * See {@link #act} method.
 */
Ext.define('Ametys.plugins.odf.catalog.SetCatalogHelper', {
    singleton: true,
    
    /**
     * Configure and open the dialog box to edit the catalog of a ODF content
     * @param {Object} config The configuration options :
     * @param {String} config.id (required) The id of content to edit
     * @param {String} [config.iconCls=odficon-book] The CSS class for icon of the dialog box
     * @param {String} [config.title={{i18n PLUGINS_ODF_HELPER_EDIT_CATALOG_TITLE}}] The title of the dialog box.
     * @param {Function} config.callback The callback function invoked when catalog is selected. The callback function will received the following parameters:
     * @param {Function} config.callback.catalog The selected catalog
     */
    act: function (config)
    {
        config = config || {};
        
        this._cbFn = config.callback;
        
        // First check if catalog can be modified
        Ametys.data.ServerComm.callMethod({
            role: "org.ametys.odf.catalog.CatalogsManager",
            methodName: "canEditCatalog",
            parameters: [config.id],
            callback: {
                handler: this._canEditCatalogCb,
                scope: this,
                arguments: {
                    config: config,
                    contentId: config.id
                }
            },
            waitMessage: true,
			errorMessage: true
        });
        
    },
    
    /**
     * @private
     * Callback function invoked after doing some server verification
     * @param {Object} result The server result
     * @param {Object} args The transmitted arguments
     */
    _canEditCatalogCb: function(result, args)
    {
        if (result.success)
        {
            var config = args
            this._createDialogBox(args.config);
        
	        // Get the current catalog
	        Ametys.data.ServerComm.callMethod({
	            role: "org.ametys.odf.catalog.CatalogsManager",
	            methodName: "getContentCatalog",
	            parameters: [args.contentId],
	            callback: {
	                handler: this._getContentCatalogCb,
	                scope: this,
	                arguments: [args.contentId]
	            },
	            waitMessage: true
	        });
        }
        else
        {
            // Catalog can not be modified
            this._handleUnmodifiableErrors(result.error);
        }
    },
    
    /**
     * @private
     * Handle unmodifiable error
     * @param {String} error the unmodifiable error
     */
    _handleUnmodifiableErrors: function(error)
    {
        var errorMsg;
        if (error == 'referenced')
        {
            errorMsg = "{{i18n PLUGINS_ODF_CONTENT_EDIT_CATALOG_REFERENCED_ERROR}}";
        }
        else if (error == 'hasSharedContent')
        {
            errorMsg = "{{i18n PLUGINS_ODF_CONTENT_EDIT_CATALOG_UNMODIFIABLE_CATALOG_ERROR}}";
        }
        else
        {
            errorMsg = "{{i18n PLUGINS_ODF_CONTENT_EDIT_CATALOG_TYPE_ERROR}}";
        }
        
        Ametys.Msg.show({
            title: "{{i18n PLUGINS_ODF_CONTENT_EDIT_CATALOG_ERROR}}",
            msg: errorMsg,
            buttons: Ext.Msg.OK,
            icon: Ext.Msg.ERROR
        });
    },
    
    /**
     * @private
     * Callback function invoked after retrieving the catalog of the current content
     * @param {String} catalogName The catalog's name
     * @param {Object[]} args The transmitted arguments
     * @param {String} args.0 The content id
     */
    _getContentCatalogCb: function(catalogName, args)
    {
        this._currentCatalogName = catalogName;
        
        var form = this._form.getForm();
        form.findField('contentId').setValue(args[0]);

        var catalogFd = form.findField('catalog');
        
        catalogFd.getStore().load(function(records, operation, success) {
            catalogFd.setValue(catalogName);
        });
        
        this._box.show();
    },
    
    /**
     * Creates the dialog box
     * @param {Object} config The configuration options:
     * @private
     */
    _createDialogBox: function (config)
    {
        if (!this._initialized)
        {
            this._form = Ext.create('Ext.form.Panel', {
	            defaults: {
	                cls: 'ametys',
	                labelSeparator: '',
	                labelAlign: 'right',
	                labelWidth: 80,
	                msgTarget: 'side',
                    width: '100%'
	            },
	            
	            border: false,
	            scrollable: true,
	            
	            items: [{
                        xtype: 'component',
                        itemId: 'hint-top',
                        cls: 'a-text',
                        html: config.helpMessage1 || "{{i18n PLUGINS_ODF_HELPER_EDIT_CATALOG_HINT_1}}"
                    },
                    {
                        xtype: 'hidden',
                        name: 'contentId'
                    },
                    Ametys.odf.catalog.CatalogDAO.createComboBox({
			            name: 'catalog',
			            itemId: 'catalog',
			            fieldLabel: "{{i18n PLUGINS_ODF_HELPER_EDIT_CATALOG_NAME}}",
			            allowBlank: false
			        }),
                    {
                        xtype: 'component',
                        itemId: 'hint-bottom',
                        cls: 'a-text',
                        html: config.helpMessage2 || "{{i18n PLUGINS_ODF_HELPER_EDIT_CATALOG_HINT_2}}"
                    }
	            ]
            });
            
            this._box = Ext.create('Ametys.window.DialogBox', {
	            title: config.title || "{{i18n PLUGINS_ODF_HELPER_EDIT_CATALOG_TITLE}}",
	            iconCls: config.iconCls || 'odficon-book',
	            
                width: 450,
	            scrollable: false,
	            
	            items: [this._form],
	            
	            closeAction: 'hide',
	            buttons : [{
	                    text : "{{i18n PLUGINS_ODF_HELPER_EDIT_CATALOG_OK}}",
	                    handler : Ext.bind(this._validate, this)
	                }, {
	                    text : "{{i18n PLUGINS_ODF_HELPER_EDIT_CATALOG_CANCEL}}",
	                    handler: Ext.bind(function() {this._box.close();}, this)
	                } 
	            ]
	        });
        }
        else
        {
            this._box.setTitle(config.title || "{{i18n PLUGINS_ODF_HELPER_EDIT_CATALOG_TITLE}}");
            this._box.setIconCls(config.iconCls || 'odficon-book');
            this._box.get('#hint-top').update(config.helpMessage1 || "{{i18n PLUGINS_ODF_HELPER_EDIT_CATALOG_HINT_1}}");
            this._box.get('#hint-bottom').update(config.helpMessage2 || "{{i18n PLUGINS_ODF_HELPER_EDIT_CATALOG_HINT_2}}");
        }
    },
    
    /**
     * Validate the dialog box and set the new catalog.
     * @private
     */
    _validate: function()
    {
        var form = this._form.getForm();
        if (!form.isValid())
        {
            return;
        }
        
        var values = form.getValues();
        if (values.catalog == this._currentCatalogName)
        {
            this._box.close();
            return;
        }
        
        var me = this;
        
        Ametys.cms.content.ContentDAO.getContent(values.contentId, function(content) {
            Ext.create("Ametys.message.Message", {
                type: Ametys.message.Message.WORKFLOW_CHANGING,
                targets: {
                    id: Ametys.message.MessageTarget.CONTENT,
                    parameters: { contents: [content] }
                }
            });
            
            Ametys.data.ServerComm.callMethod({
	            role: "org.ametys.odf.catalog.CatalogsManager",
	            methodName: "setContentCatalog",
	            parameters: [values.catalog, values.contentId],
	            callback: {
	                handler: me._setContentCatalogCb,
	                scope: me,
	                arguments: [content],
                    ignoreOnError: false
	            },
	            errorMessage: "{{i18n PLUGINS_ODF_HELPER_EDIT_CATALOG_ERROR}}",
	            waitMessage: true
	        });
        });
    },
    
    /**
     * @private
     * Callback function after setting the catalog
     * @param {Object} response The server response
     * @param {Object} args The callback arguments
     */
    _setContentCatalogCb: function(response, args)
    {
        // Always send a workflow changed event to rollback the workflow changing event
        Ext.create("Ametys.message.Message", {
            type: Ametys.message.Message.WORKFLOW_CHANGED,
            targets: {
                id: Ametys.message.MessageTarget.CONTENT,
                parameters: { contents: [args[0]] }
            }
        });
        
        // Response is undefined in case of error
        if (response !== undefined)
        {
            this._box.close();
            
	        Ext.create("Ametys.message.Message", {
	            type: Ametys.message.Message.MODIFIED,
	            targets: {
	                id: Ametys.message.MessageTarget.CONTENT,
	                parameters: { contents: [args[0]] }
	            }
	        });
	        
	        if (Ext.isFunction(this._cbFn))
	        {
	            this._cbFn(args[0]);
	        }
        }
        
    }
});