/*
 *  Copyright 2023 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 is used for the steering buttons of MCC workflow
 */
Ext.define('Ametys.plugins.odf.pilotage.controller.MCCWorkflowMenu', {
    extend: 'Ametys.plugins.cms.content.controller.SmartContentController',
    
    /**
     * @property
     * @type {Number} MAX_CONTENTS_IN_TOOLTIP
     */
    MAX_CONTENTS_IN_TOOLTIP: 5,
    
    /**
     * @cfg {String} mcc-status The MCC status of this controller
     */
    /**
     * @property {String} _mccStatus See #cfg-mcc-status
     * @private
     */
    
    /**
	 * @cfg {String} on-icon-decorator The CSS class for icon decorator when the workflow status is on.
	 */
	/**
	 * @property {String} _onIconDecorator See #cfg-on-icon-decorator
	 * @private
	 */
    
    constructor: function(config)
    {
        this.callParent(arguments);
        
        this._mccStatus = this.getInitialConfig("mcc-status");
        this._onIconDecorator = this.getInitialConfig("on-icon-decorator");
		
        Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onModified, this);
    },
    
    /**
     * @private
     * Listener handler for modified messages
     * @param {Ametys.message.Message} message the message
     */
    _onModified: function(message)
    {
        if (this.updateTargetsInCurrentSelectionTargets(message))
        {
            this.refresh();
        }
    },
    
    /**
	 * Refresh the controller from the content informations state of given targets
	 * @param targets The content targets
	 * @protected
	 */
	_getStatus: function (targets)
	{
		this.disable();
		
		var contentIds = [];
		for (var i=0; i < targets.length; i++)
		{
			contentIds.push(targets[i].getParameters().id);
		}
        
		this.serverCall ('getStatus', [contentIds, this._mccStatus], this._getStatusCb, {arguments: targets,  cancelCode: this.self.getName() + "$" + this.getId(), refreshing: true });
	},
    
    /**
	 * @protected
	 * Callback for the button reloading process
     * @param {Object} params the server's response
     */
	_getStatusCb: function (params, targets)
	{
		this.callParent(arguments);
		
		if (this._toggleEnabled)
		{
			var activeContents = params['active-contents'];
			this.toggle(activeContents.length > 0);
		}
        
		this._updateIconDecorator(params);

        if (this.isDisabled())
        {
            return;
        }
		
		if (this._getMenuItems().length == 0)
		{
			this.disable();
		}
	},
    
    /**
     * @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)
    {
		description = this._handlingMultiple(description, "active", params['active-contents']);
        description = this._handlingMultiple(description, "valid", params['valid-contents']);
        description = this._handlingMultiple(description, "noyear", params['noyear-contents']);
        description = this._handlingMultiple(description, "noright", params['noright-contents']);
        description = this._handlingMultiple(description, "locked", params['locked-contents']);
		description = this._handlingMultiple(description, "noread", params['noread-contents']);
        
        this.setDescription (description);
    },
    
    // Override to add "... and X others"
    _handlingMultiple: function(description, prefix, contents)
    {
        if (contents && contents.length > 0)
        {
            if (description != "")
            {
                description += "<br/><br/>";
            }
            
            description += this.getInitialConfig(prefix + "-start-description");
            for (var i=0; i < Math.min(this.MAX_CONTENTS_IN_TOOLTIP, contents.length); i++)
            {
                if (i != 0) 
                {
                    description += ", ";
                }
                description += contents[i].description;
            }
            
            let remainingContents = contents.length - this.MAX_CONTENTS_IN_TOOLTIP;
            if (remainingContents == 1)
            {
                description += "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_MCC_WORKFLOW_TOOLTIP_REMAINING_CONTENT}}";
            }
            else if (remainingContents > 1)
            {
                description += Ext.String.format("{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_MCC_WORKFLOW_TOOLTIP_REMAINING_CONTENTS}}", remainingContents);
            }
            
            description += this.getInitialConfig(prefix + "-end-description");
        }
        
        return description;
    },
	
	/**
	 * @private
	 * Update the icon's decorator
	 * @param {Object} params The JSON result 
	 */
	_updateIconDecorator: function (params)
	{
        var activeContents = Ext.Array.merge(params['active-contents'], params['valid-contents']);
		if (activeContents.length > 0 && this._onIconDecorator)
		{
			this.setIconDecorator(this._onIconDecorator);
		}
		else
		{
			this.setIconDecorator(null);
		}
	}
});