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

/**
 * @private
 * This class control a menu sub-item with content types as sub-items
 * On show event, the items of this menu item will be checked/unchecked according the current selected content
 */
Ext.define('Ametys.plugins.cms.content.controller.ContentTypeMenuItemController', {
	extend: 'Ametys.ribbon.element.ui.ButtonController',
	
	/**
	 * @inheritdoc
	 * Add a listener on 'menushow' event
	 */
	createMenuItemUI: function ()
	{
		var elt = this.callParent(arguments);
		elt.menu.on ('show', this._onMenuShow, this);
		return elt;
	},
	
	/**
	 * Listener on 'menushow' event<br>
	 * @param {Ext.menu.Menu} menu The menu
	 * @private
	 */
	_onMenuShow: function (menu)
	{
		var target = this.getMatchingTargets()[0];
		
		this._mask = Ext.create('Ext.LoadMask', {
			target: menu,
			msg: "{{i18n plugin.core-ui:PLUGINS_CORE_UI_LOADMASK_DEFAULT_MESSAGE}}"
		});
		this._mask.show();
		
		// Current content types can not be up-to-date, send request to update
		var content = Ametys.cms.content.ContentDAO.getContent(target.getParameters().id, Ext.bind(this._fillGallery, this, [menu], 1));
	},
	
	/**
	 * Fill the gallery 
	 * @param {Ametys.cms.content.Content} content The current content
	 * @param {Ext.menu.Menu} menu the menu
	 * @private
	 */
	_fillGallery: function (content, menu)
	{
		var cTypes = content.getTypes();
		
		menu.items.each(function (item) {
			var contentTypeController = Ametys.ribbon.RibbonManager.getUI(item.controlId);
			var cTypeId = contentTypeController.getInitialConfig('contentTypes');
			
			var state = Ext.Array.contains(cTypes, cTypeId);
			contentTypeController.toggle(state);
		});
		
		if (this._mask)
		{
			this._mask.hide();
			this._mask = null;
		}
	}
});