/*
 *  Copyright 2022 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 that is able to check if the ODF content is publishable
 * @private
 */
Ext.define('Ametys.plugins.odf.content.controller.IsPublishableODFContentController', {
    extend: 'Ametys.ribbon.element.ui.ButtonController',
    
    constructor: function (config)
    {
        this.callParent(arguments);
        
        Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onModified, this);
    },
    
    /**
     * Listener on modified message.
     * Update the state of the controller accordingly.
     * @param {Ametys.message.Message} message the message of type modified.
     * @private
     */
    _onModified: function(message)
    {
        if (this.updateTargetsInCurrentSelectionTargets(message))
        {
            this.refresh();
        }
    },
    
    updateState: function ()
    {
        this.refreshing();
        this.disable();
            
        this._getStatus(this.getMatchingTargets());
    },
    
    /**
     * Refresh the controller from the informations state of given targets
     * @param {Ametys.message.MessageTarget[]} targets The targets
     * @protected
     */
    _getStatus: function (targets)
    {
        var description = this.getInitialConfig("description") || this.getInitialConfig("default-description") || '';
        // Multiselection is disabled
        var matchingTarget = targets[0];
        
        var errorDescription = "";
        if (!matchingTarget.getParameters().additionalData.isPublishable)
        {
            errorDescription = this.getConfig("not-publishable-description");
        }
        
        if (errorDescription == '')
        {
            this.enable();
        }
        else
        {
            if (description != '')
            {
                description += "<br/><br/>";
            }
            description += errorDescription;
            this.disable();
        }
        
        this.stopRefreshing();
        this.setDescription (description);
    }
});