/*
 *  Copyright 2014 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 button allows to remove a referenced content from its parent in the current selection.
 * The message bus target must have an additionnal parameter "parentNode"
 */
Ext.define('Ametys.plugins.contentstree.RemoveFromCurrentSelectionButtonController', {
    extend: "Ametys.ribbon.element.ui.ButtonController",
    
    /**
     * @cfg {String} editWorkflowActionId (required) This is the value of the edit action in the workflow of the parent object. If the action is not available, the button will remain grayed.
     */
    
    /**
     * @cfg {String} unavailable-workflowaction-description The description when the workflow action is not available on parent object.
     */
    
    /**
     * @cfg {String} [action=Ametys.plugins.contentstree.RemoveFromCurrentSelectionButtonController.act] Action to execute on clic 
     */
    
    statics: {
        /**
         * @private
         * The action of this controller
         * @param {Ametys.ribbon.element.ui.ButtonController} controller The button controller
         * @param {Boolean} state The toggle state or null
         */
        act: function(controller, state)
        {
            var target = controller.getMatchingTargets()[0];
            var me = controller;
            
            if (target != null)
            {
                Ametys.plugins.contentstree.RemoveFromCurrentSelectionButtonController.remove(target, me.getInitialConfig("editWorkflowActionId"));
            }
        },
        
        /**
         * Remove the referenced content from its parent
         * @param {Ametys.message.MessageTarget} target The target of content to remove
         * @param {Number|String} editWorkflowActionId The edit workflow action id
         */
        remove: function (target, editWorkflowActionId)
        {
            Ametys.data.ServerComm.callMethod({
                    role: "org.ametys.core.ui.RelationsManager",
                    id: "org.ametys.cms.relations.setcontentattribute",
                    methodName: "setContentAttribute",
                    parameters: [
                        [],
                        {},
                        [{
                            referencingAttributePath: target.getParameters().parentMetadataPath,
                            contentId: target.getParameters().parentNode,
                            valueToRemove: target.getParameters().id
                        }],
                        "",
                        [editWorkflowActionId]
                    ],
                    callback: {
                        handler: function(response, args) {
                            if (response == null)
                            {
                                Ametys.log.ErrorDialog.display({
                                    title: "{{i18n PLUGINS_CONTENTSTREE_REMOVEELEMENT_NOTREMOVED_TITLE}}",
                                    text: "{{i18n PLUGINS_CONTENTSTREE_REMOVEELEMENT_NOTREMOVED_TEXT}}",
                                    category: this.self.getName()
                                });
                            }
                            else
                            {
                                var details = "";
                                for (var i = 0; response['errorMessages'] && i < response['errorMessages'].length; i++)
                                {
                                    details = response['errorMessages'][i] + "\n";
                                }
                                if (details != "")
                                {
                                    Ametys.log.ErrorDialog.display({
                                        title: "{{i18n PLUGINS_CONTENTSTREE_REMOVEELEMENT_NOTREMOVED_TITLE}}",
                                        text: "{{i18n PLUGINS_CONTENTSTREE_REMOVEELEMENT_NOTREMOVED_TEXT}}",
                                        details: details,
                                        category: this.self.getName()
                                    });
                                }

                                if (response['success'] == true)
                                {
                                    Ext.create("Ametys.message.Message", {
                                        type: Ametys.message.Message.MODIFIED,
                                        
                                        targets: {
                                            id: target.getId(),
                                            parameters: { ids: [target.getParameters().parentNode]}
                                        },
                                        
                                        parameters: {
                                            major: false
                                        }
                                    });
                                }
                            }
                        },
                        arguments: null
                    },
                    waitMessage: true
                });
        }
    },
    
    /**
     * @cfg {String} action Hardcoded to "Ametys.plugins.contentstree.RemoveFromCurrentSelectionButtonController#act"
     * @private
     */
    
    constructor: function(config)
    {
        config['action'] = config['action'] || "Ametys.plugins.contentstree.RemoveFromCurrentSelectionButtonController.act";
        
        this.callParent(arguments);
    },
    
    updateState: function ()
    {
        var target = this.getMatchingTargets()[0]; // multilection not supported (here assume that the number of matching targets is equals to 1)
        
        // Status should be check on parent node
        var parentId = target.getParameters().parentNode;
        var me = this;
        
        Ametys.cms.content.ContentDAO.getContent(parentId, function(content) {
            me.stopRefreshing(true);
            me._getParentStatus(content, target);
        });
    },
    
    /**
     * @protected
     * Get the parent status
     * @param {Ametys.cms.content.Content} content the parent content
     * @param {Ametys.message.MessageTarget} target the matching target
     */
    _getParentStatus: function(content, target)
    {
        if (!Ext.Array.contains(content.getAvailableActions(), parseInt(this.getInitialConfig("editWorkflowActionId"))))
        {
            this.setAdditionalDescription(this.getInitialConfig("unavailable-workflowaction-description") || this.getInitialConfig("error-description"));
            this.disable();
            
        }
        else if (!this._hasRight(content))
        {
            this.setAdditionalDescription(this.getInitialConfig("rights-description-no") || this.getInitialConfig("error-description"));
            this.disable();
        }
        else
        {
            this.setAdditionalDescription("");
            this.enable();
        }
    },
    
    /**
     * @private
     */
    _hasRight: function(content)
    {
        var rightToCheck = this.getInitialConfig("parent-rights");
        if (!rightToCheck)
        {
            // No right is needed: ok.
            return true;
        }
            
        var rights = content.getRights();
        var neededRights = rightToCheck.split('|');
        for (var i=0; i < neededRights.length; i++)
        {
            if (Ext.Array.contains(rights, neededRights[i]))
            {
                return true;
            }
        }
        
        return false;
    }
    
});