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

/**
 * Model menu button for the list of designs in the skin
 */
Ext.define('Ametys.plugins.skinfactory.ribbon.menu.DesignsMenu', {
	extend: 'Ametys.ribbon.element.ui.ButtonController',
	
    /**
     * @property {Ext.menu.Menu} _menu The menu referencing the design menu items.
     * @private
     */
	
	constructor: function(config)
	{
		this.callParent(arguments);
		
		Ametys.message.MessageBus.on(Ametys.message.Message.LOADED, this._onSkinLoaded, this);
	},

	createUI: function(size, colspan)
	{
		var element = this.callParent(arguments);
	
		var menu = element.getMenu();
        this._getGalleries(element).each(function(gallery) {
    		gallery.items.each(function (item) {
    			item.setVisible(false);
    		});
        });
		
		return element;
	},
	
	/**
	 * @private
	 * Listener when the skin is loaded. Get the available languages of the current skin.
	 * @param {Ametys.message.Message} message The loaded message on bus
	 */
	_onSkinLoaded: function(message)
	{
		var target = message.getTarget(Ametys.message.MessageTarget.SKIN);
        if (target)
        {
        	Ametys.plugins.skincommons.helper.SkinHelper.getSkinModel(Ametys.plugins.skinfactory.skin.SkinDAO.SERVER_ROLE, null, target.getParameters().name, "temp", Ext.bind(this._getSkinModelCb, this));
        }
	},
	
	/**
	 * Callback after retrieving the model name for the skin.
	 * @param {String} skinName The skin name
	 * @param {String} modelName The model name
	 */
	_getSkinModelCb: function (skinName, modelName)
	{
		var hasDesigns = false;
		
		this._getGalleries().each (function (galery) {
			galery.items.each(function (item) {
				var controller = Ametys.ribbon.RibbonManager.getUI(item.controlId);
				var model = controller.getInitialConfig("modelName");
				item.setVisible(modelName == model);
				hasDesigns = hasDesigns || (modelName == model);
			});
		});
		
		if (!hasDesigns)
		{
			this.setAdditionalDescription(this.getInitialConfig("design-description-empty"));
			this.disable();
		}
		else
		{
			this.setAdditionalDescription("");
			this.enable();
		}
	}
});