/*
 *  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 class controls a ribbon button enabling when a hierarchical simple content, non-leaf (i.e. can have children) is selected.
  * @private
  */
Ext.define('Ametys.plugins.cms.content.controller.HierarchicalReferenceTablesController', {
    extend: 'Ametys.ribbon.element.ui.ButtonController',
    
    /**
     * @cfg {String} workflow-name The name of the workflow for simple contents
     */
    /**
     * @cfg {String} workflow-action-id The id of the workflow action to perform
     */
    /**
     * @cfg {String} content-language The language for the contents
     */
    
    updateState: function()
    {
        this.disable();
        
        var targetId = this.getInitialConfig("selection-target-id") || this.getInitialConfig("target-id"); 
        var regex = new RegExp(targetId);

        var targets = this.getMatchingTargets();
        
        if (targets.length == 1)
        {
            var target = targets[0],
                targetId = target.getId();
            if (targetId == Ametys.message.MessageTarget.REFERENCE_TABLE_CONTENT)
            {
                var contentId = target.getParameters().id;
                this.serverCall("canHaveChild", [contentId], this._canHaveChildCb, {refreshing: true});
            }
            else if (targetId == Ametys.message.MessageTarget.REFERENCE_TABLE_CONTENT_ROOT)
            {
                // Root of hierarchy, can always have children
                this._canHaveChildCb(true);
            }	
        }
    },
    
    /**
     * @private
     * Callback function called after server 
     * @param {Boolean} returnedValue True if the selected simple content id can have a child.
     */
    _canHaveChildCb: function(returnedValue)
    {
        if (returnedValue)
        {
            this.enable();
            this.setAdditionalDescription("");
        }
        else
        {
            this.disable();
            this.setAdditionalDescription(this.getInitialConfig("selection-description-nomatch"));
        }
    }
});