/*
 *  Copyright 2020 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 for adding a task.
 * One of the parameters of the schedulable depends of the current selection in the UI.
 * @private
 */
Ext.define('Ametys.plugins.coreui.schedule.SelectionAwareAddTaskButtonController', {
    extend: 'Ametys.plugins.coreui.schedule.AddTaskButtonController',
    
    inheritableStatics: {
        /**
         * The action for this controller that will set the configured parameter in the 'schedulable-parameters' object
         * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller
         */
        act: function(controller)
        {
            var targets = controller.getMatchingTargets();
            if (this._isSelectionOk(targets))
            {
                controller['schedulable-parameters'] = controller['schedulable-parameters'] || {};
                controller['schedulable-parameters'][this._getParamName(controller)] = this._getParamValue(targets);
                
                this.callParent(arguments);
            }
        },
        
        /**
         * Check if the selection contains necessary information
         * @protected
         * @param {Ametys.message.MessageTarget[]} targets the selected targets matching the configuration
         * @return {Boolean} true if the selection is ok, false otherwise
         */
        _isSelectionOk: function(targets)
        {
            return targets.length > 0;
        },
        
        /**
         * Get the parameter value for the schedulable
         * @protected
         * @param {Ametys.message.MessageTarget[]} targets the selected targets matching the configuration
         * @return {String} the parameter value
         */
        _getParamValue: function(targets)
        {
            return targets[0].getParameters().id;
        },
        
        /**
         * Get the parameter name for the schedulable
         * @protected
         * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller
         * @return {String} the parameter name
         */
        _getParamName: function(controller)
        {
            return controller.getInitialConfig('schedulable-param-name');
        }
    }
});