/*
 *  Copyright 2013 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 enabled if at least one page on the current selection fills the following conditions:<br/>
 * - page is not a page of redirection<br/>
 * - page is modifiable<br/>
 * - user has convenient right on page
 * @private
 */
Ext.define('Ametys.plugins.web.page.controller.ServiceMenuController', {
	extend: 'Ametys.web.controller.WebButtonController',
	
	/**
	 * @property {String[]} [_pageIds=[]] List of identifiers of pages concerned by the action of the controller
	 * @private
	 */
	
	constructor: function(config)
	{
		this.callParent(arguments);
		Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onMessageModified, this);
	},
	
	_onMessageModified: function(message)
	{
		if (this.updateTargetsInCurrentSelectionTargets (message))
	    {
	        this.refresh();
	    }
	},
	
	updateState: function()
	{
		this._getStatus(this.getMatchingTargets());
	},
	
	areSameTargets: function(target1, target2)
	{
		var match = this.callParent(arguments);
		return match && target1.getParameters()['zone-name'] == target2.getParameters()['zone-name'];
	},
	
	/**
	 * Get the lock state of given targets
	 * @param targets The page targets
	 * @private
	 */
	_getStatus: function (targets)
	{
		this.disable();
		
		if (targets.length > 0)
		{
			var pageId = targets[0].getParameters().id;
			var zoneName = targets[0].getParameters()['zone-name'];
			this.serverCall ('getAvailableServices', [pageId, zoneName], this._getAvailableServicesCb, { errorMessage: true, refreshing: true });
		}
	},
	
	/**
	 * @private
	 * Callback function called after retrieving the status of page targets
	 * @param params The JSON result 
	 */
	_getAvailableServicesCb: function (params)
	{
		var services = params.services;
		
        this._getGalleries().each(function (gallery) {
            var atLeastOneAvailable = false;

            gallery.items.each (function (item) {
                var elmt = Ametys.ribbon.RibbonManager.getUI(item.controlId);
                
                var available = Ext.Array.contains(services, elmt.serviceId);
                item.setVisible(available);
                
                atLeastOneAvailable = atLeastOneAvailable || available
            });
            atLeastOneAvailable ? gallery.show() : gallery.hide();
        });
        
		if (services.length > 0 && !params['noright-page'] && !params['nomodifiable-page'] && !params['locked-page'])
		{
			this.enable();
		}
		else
		{
			this.disable();
		}
		
		this._updateTooltipDescription(this.getInitialConfig('description'), params);
	},
	
	/**
	 * @protected
	 * Update the tooltip description according state of the current selection
	 * @param description The initial description. Can be empty.
	 * @param params The JSON result received
	 */
	_updateTooltipDescription: function (description, params)
	{
		if (params.services.length == 0)
		{
			if (description != "")
			{
				description += "<br/><br/>";
				description += this.getInitialConfig('noservice-description');
			}
		}
		
		if (params['noright-page'])
		{
			if (description != "")
			{
				description += "<br/><br/>";
				description += this.getInitialConfig('rights-description-no');
			}
		}
		
		if (params['nomodifiable-page'])
		{
			if (description != "")
			{
				description += "<br/><br/>";
				description += this.getInitialConfig('modifiable-description-no');
			}
		}
		
		if (params['locked-page'])
		{
			if (description != "")
			{
				description += "<br/><br/>";
				description += this.getInitialConfig('selection-locked-description');
			}
		}
		
		this.setDescription (description);
	}
});