/*
 *  Copyright 2015 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.
 */
 
/**
 * Abstract base class for button controller dealing with the repository.
 * These buttons are automatically disabled if a maintenance task is launched.
 */
Ext.define('Ametys.repository.controller.RepositoryButtonController', {
    extend: 'Ametys.ribbon.element.ui.ButtonController',
    
    /**
     * @property {Boolean} _repositoryAvailable True is the repository is available
     * @private
     */
    
    constructor: function(config)
    {
        this.callParent(arguments);
        
        // Repository state
        this._repositoryAvailable = true;
        
        // Bus messages listeners
        Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._disableOnMaintenance, this);
    },
    
    /**
	 * Called on each modified message. Looks for
	 * {@link Ametys.message.MessageTarget#APPLICATION} message target, and
	 * disable the button if status 'REPOSITORY_UNAVAILABLE' is present.
	 * @param {Ametys.message.Message} message The bus message.
	 * @private
	 */
    _disableOnMaintenance: function(message)
    {
        var target = message.getTarget(Ametys.message.MessageTarget.APPLICATION, 1),
            status;
        if (target)
        {
            status = target.getParameters().status.current || [];
            
            // Repo became unavailable
            if (this._repositoryAvailable && Ext.Array.contains(status, 'REPOSITORY_UNAVAILABLE'))
            {
                this.disable();
                this.setAdditionalDescription("{{i18n PLUGINS_REPOSITORYAPP_BUTTON_REPOSITORY_UNAVAILABLE_DESC}}");
                this._repositoryAvailable = false;
            }
            // Repo became available
            else if (!this._repositoryAvailable && !Ext.Array.contains(status, 'REPOSITORY_UNAVAILABLE'))
            {
                this._repositoryAvailable = true;
            }
        }
    }
});