/*
 *  Copyright 2016 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.
 */

/**
 * Resources context for profile assignments.
 */
Ext.define('Ametys.plugins.explorer.profiles.ResourceRightAssignmentContext', {
    extend: 'Ametys.plugins.coreui.profiles.AbstractRightAssignmentContext',
    
    /**
     * @private
     * @property {Ametys.explorer.tree.ExplorerTree} _tree The explorer tree
     */
    /**
     * @private
     * @property {Boolean} _initialized true if the root node of the tree is initialized
     */
    _initialized: false,
    
    getComponent: function()
    {
        this._tree = this._createTree();
        return this._tree;
    },
    
    initialize: function()
    {
        if (!this._initialized)
        {
            this._refreshMask = Ext.create("Ext.LoadMask", {msg: "{{i18n plugin.core-ui:PLUGINS_CORE_UI_MSG_TOOLS_REFRESHING}}", target: this._tree});
            this._refreshMask.show();
            Ametys.explorer.ExplorerNodeDAO.getRootNodesInfo(this._setRootNodesCb, this, null, null, null);
        }
        else
        {
            this._tree.getSelectionModel().deselectAll();
            this._tree.getSelectionModel().select(this._tree.getRootNode().firstChild);
        }
    },
    
    isSupported: function (message)
    {
    	return message.getTargets(Ametys.message.MessageTarget.EXPLORER_COLLECTION).length > 0;
    },
    
    initContext: function (message)
    {
    	var target = message.getTarget(Ametys.message.MessageTarget.EXPLORER_COLLECTION);
    	if (target != null)
    	{
    		this._pathToSelect = target.getParameters().pathPrefix + target.getParameters().path;
    	}
    	else
    	{
    		this._pathToSelect = null;
    	}
    },
    
    /**
     * @private
     * Create the explorer tree
     * @return {Ametys.explorer.tree.ExplorerTree} The created explorer tree
     */
    _createTree: function()
    {
        return Ext.create('Ametys.explorer.tree.ExplorerTree', {
            inlineEditionEnable: false,
            border: false,
            ignoreFiles: true,
            listeners: {
                'selectionchange': Ext.bind(this._onSelectionChanged, this),
                'destroy': Ext.bind(function(ct) {
                    this._initialized = false;
                }, this)
            }
        });
    },
    
    /**
     * @private
     * Callback after setting the root node of the tree
     * @param {Object[]/Object} response the server response
     */
    _setRootNodesCb: function(response)
    {
        if (response)
        {
            this._tree.setRootNodes(response);

            this._tree.getRootNode().expandChildren(false, false, function() {
                if (this._pathToSelect != null)
                {
                    this._tree.selectByPath(this._pathToSelect);
                }
                else
                {
                    this._tree.getSelectionModel().select(this._tree.getRootNode().firstChild);
                }
            }, this);
        }
        
        this._refreshMask.hide();
        Ext.destroy(this._refreshMask);
        this._refreshMask = null;

    	this._initialized = true;
    },
    
    /**
     * @private
     * Listener when the selection in the tree has changed
     * @param {Ext.selection.Model} model The selection model
     * @param {Ext.data.Model[]} selected The selected records
     */
    _onSelectionChanged: function(model, selected)
    {
        if (selected.length > 0)
        {
            var resourceOrRoot = selected[0],
                object = resourceOrRoot.get('id'),
                type = resourceOrRoot.get('type'),
                title = resourceOrRoot.get('text'),
                isRoot = Ext.Array.contains(this._tree.getRootIds(), object);
            
            var hintTextContext;
            if (isRoot)
            {
                hintTextContext = this.getRootContextHintText(resourceOrRoot);
            }
            else
            {
                hintTextContext = type == Ametys.explorer.tree.ExplorerTree.RESOURCE_TYPE ? "{{i18n PLUGINS_EXPLORER_RIGHT_ASSIGNMENT_CONTEXT_RESOURCES_HINT_RESOURCE}} <b>" + title + "</b>"
                                                                                          : "{{i18n PLUGINS_EXPLORER_RIGHT_ASSIGNMENT_CONTEXT_RESOURCES_HINT_COLLECTION}} <b>" + title + "</b>";
            }
            
            this._changeObjectContext(object, hintTextContext, false, isRoot);
        }
    },
    
    /**
     * Returns the hint text to display for a root node
     * @param {Ext.data.Model} rootNode The selected root node
     */
    getRootContextHintText: function (rootNode)
    {
    	return "<b>{{i18n PLUGINS_EXPLORER_RIGHT_ASSIGNMENT_CONTEXT_RESOURCES_HINT_ALL}}</b>";
    }
});