/*
 *  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 class controls a ribbon menu allowing to select the view for the selected content
 * @private
 */
Ext.define('Ametys.plugins.web.zone.controller.ContentViewController', {
	extend: 'Ametys.plugins.web.zone.controller.ModifiableZoneItemController',
	
	
	constructor: function(config)
	{
		this.callParent(arguments);
		
		Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onModified, this);
	},

	/**
	 * Function invoked when a 'modified' message is sent out on the bus
	 * @param {Ametys.message.Message} message The bus message
	 * @private
	 */
	_onModified: function(message)
	{
		if (this.updateTargetsInCurrentSelectionTargets (message))
		{
    		this.refresh();
		}
	},
	
	updateState: function()
	{
		var targets = this.getMatchingTargets();
		if (targets.length > 0)
		{
			var contentTargets = targets[0].getSubtargets(function (target) { return target.getId() == Ametys.message.MessageTarget.CONTENT });
			if (contentTargets.length > 1)
			{
				this.setAdditionalDescription(this.getInitialConfig('selection-description-multiselectionforbidden-content'));
				this.disable();
			}
			else
			{
				this.enable();
				this.setAdditionalDescription('');
				
                // First hide all (while asking server)
                this._getGalleries().each(function (gallery) {
                    gallery.setVisible(false);
                });
                
                
				var zoneItemTarget = targets[0].getSubtargets(Ametys.message.MessageTarget.ZONE_ITEM).filter(t => t.getSubtarget("content") != null)[0]; // Event if targets if fine, subtargets can have non content and content: we need to filter to find the zoneitem with content
				
                // Then ask server
                this.serverCall("getViews", [zoneItemTarget.getParameters().id], Ext.bind(this._updateStateCb, this), {errorMessage: true, arguments: [contentTargets, zoneItemTarget]});
			}
		}
	},
    
    _updateStateCb: function(views, args)
    {
        let contentTargets = args[0], 
            zoneItemTarget = args[1];
        
        var selectedContentType = contentTargets[0].getParameters().types[0];
        var viewName = zoneItemTarget.getParameters().viewName;

        this._getGalleries().each(function (gallery) {
            var atLeastOneItemVisible = false;
            
            gallery.items.each (function (item) {
                var galleryElement = Ametys.ribbon.RibbonManager.getUI(item.controlId);
                
                atLeastOneItemVisible = atLeastOneItemVisible || (selectedContentType == galleryElement.contentType);
                item.setVisible(selectedContentType == galleryElement.contentType 
                                && (!galleryElement.skinName || galleryElement.skinName == Ametys.getAppParameter("skin"))
                                && (views == null || views[selectedContentType] == null || views[selectedContentType].includes(galleryElement.name)));
                galleryElement.toggle(galleryElement.name == viewName);
            });
            
            gallery.setVisible(atLeastOneItemVisible);
        });
    }
});