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

/**
 * Selection tool that react to selection of right context.
 * If the current selection is not a right context or no selection is present,
 * the tool will "select" the general context
 */
Ext.define('Ametys.plugins.coreui.rights.RightContextSelectionTool', {
    extend: "Ametys.tool.SelectionTool",

    /**
     * @private
     * @property {boolean} _convertors the list of all the registered
     * TargetToContextConvertor instance
     */
    
    constructor: function(config)
    {
        this.callParent(arguments);
        
        // Add the selection changed listener because we listen to all bus message
        Ametys.message.MessageBus.on(Ametys.message.Message.SELECTION_CHANGED, this._onSelectionChanged, this);
        

        // Instantiate all the convertor once and for all
        this._convertors = [];
        for (idx in config.convertors)
        {
            var convertor = Ext.create(config.convertors[idx].className, config.convertors[idx].parameters);
            convertor.setServerId(config.convertors[idx].serverId);
            this._convertors.push(convertor)
        }
    },
    
    _isRefreshNeeded: function (message)
    {
        // Override to refresh for empty selection
        if (message.getTargets().length == 0)
        {
            // refresh only if the selection was not already a empty selection
            if (this._currentSelectionTargets == null // invalid selection
                || this._currentSelectionTargets.length > 0) // non empty selection
            {
                this._currentConvertorIdx = null;
                this._currentSelectionTargets = [];
                return true;
            }
            else
            {
                return false;
            }
        }
        
        return this.callParent(arguments);
    },

    _getMatchingSelectionTargets: function(message)
    {
        var me = this;
        // reset the matching convertor
        me._matchingConvertorIdx = null;
        return message.getTargets(
            function(target)
            {
                for (idx in me._convertors)
                {
                    if (me._convertors[idx].isSupportedTarget(target))
                    {
                        // store the matching convertor to update current convertor
                        // once its confirmed that the selection changed
                        me._matchingConvertorIdx = idx;
                        return true;
                    }
                }
                return false;
            }
        );
    },
    
    _isCurrentSelectionChanged: function(message)
    {
        var changed = this.callParent(arguments);
        if (changed)
        {
            // The selection has changed. Update the current convertor
            this._currentConvertorIdx = this._matchingConvertorIdx;
        }
        return changed;
    },

    // Overrides to allow target to context convertor to provide their own definition of
    // same targets
    areSameTargets: function(target1, target2)
    {
        // to be the same, two target must be handled by the same convertor
        if (this._currentConvertorIdx == this._matchingConvertorIdx)
        {
            return this._convertors[this._currentConvertorIdx].areSameTargets(target1, target2);
        }
        return false;
    },

    /**
     * Get the context id of the target
     * @param target a target provided by the getCurrentSelectionTargets method
     * @returns the context id
     */
    getContextId: function(target)
    {
        return this._currentConvertorIdx != null ? this._convertors[this._currentConvertorIdx].convert(target) : null;
    },
    
    /**
     * Get the context info of the target
     * @param target a target provided by the getCurrentSelectionTargets method
     * @returns the context info
     */
    getContextInfo: function(target)
    {
        return this._currentConvertorIdx != null ? this._convertors[this._currentConvertorIdx].getContextInfo(target) : {label:"{{i18n PLUGINS_CORE_UI_RIGHTS_EXPLAIN_TOOL_CONTEXT_WORKSPACE_CONTEXT_LABEL}}"};
    },
    
    getConvertorId: function()
    {
        return this._currentConvertorIdx != null ? this._convertors[this._currentConvertorIdx].getServerId() : null;
    }
});