/*
 *  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.
 */

/**
 * This controller handles the status of the menu
 */
Ext.define('Ametys.plugins.forms.content.controller.FormsController', {
	
	extend: 'Ametys.ribbon.element.ui.ButtonController',
	
	constructor: function(config)
	{
		this.callParent(arguments);
		
		Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onModified, this);
	},
	
	/**
	 * @private
	 * Listener for modified messages
	 * Will update the state of the buttons effectively upon the current selection.
	 * @param {Ametys.message.Message} message the message.
	 */
	_onModified: function (message)
	{
		if (this.updateTargetsInCurrentSelectionTargets (message))
		{
			this.refresh();
		}
	},
	
	updateState: function()
	{
    	this._getStatus(this.getMatchingTargets());
	},

	/**
	 * @private
	 * Get the status of the button
	 * @param targets The content targets
	 */
	_getStatus: function(targets)
	{
		this.disable();
		
		var contentIds = [];
		for (var i=0; i < targets.length; i++)
		{
			contentIds.push(targets[i].getParameters().id);
		}
		
		this.disable();

		this.serverCall('getStatus',
			[contentIds], 
			Ext.bind(this._getStatusCb, this),
			{ 
				errorMessage: true,
                refreshing: true,
				arguments: {
					targets: targets
				}
			}
		);
	},
	
	/**
	 * @private
	 * Callback for the button reloading process
	 * @param {Object} params the server's response
	 * @param {Object[]} params.forms the forms
	 * @param {String} params.forms.id the id of the form
	 * @param {String} params.forms.label the label of the form
	 * @param {String} params.content-id the id of the content
	 * @param {String} params.content-title the title of the content
	 */
	_getStatusCb: function(params, args)
	{
	    this.setDisabled(params.forms.length < 1);
		
		var additionalDesc = "";
		
		if (params.forms.length == 0)
		{
			additionalDesc += this.getInitialConfig('no-form-description');
		}
		
		var noRightContents = params['noright-contents'] || [];
		if (noRightContents.length > 0)
		{
			var contentTitles = Ext.Array.filter(args.targets, t => Ext.Array.contains(noRightContents, t.getParameters().id)).map(t => t.getParameters().title);
			if (additionalDesc.length)
			{
				additionalDesc += "<br/><br/>";
			}
			additionalDesc += this.getInitialConfig('no-right-description') + contentTitles.join(", ");
		}
		
	    this.setAdditionalDescription(additionalDesc);
	}
});