/*
 *  Copyright 2024 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 tab does display the properties of the current selected target..
 * It is an element of the properties tool.
 * The tab is hidden if no target matched.
 * @private
 */
Ext.define('Ametys.plugins.cms.properties.PropertiesTab', {
    extend: "Ametys.tool.SelectionTool",
    
    /**
     * @property {Object} _parentTool The parent tool identifier
     * @private
     */
    _parentTool: null,
    
    constructor: function(config)
    {
        this.callParent(arguments);
        
        Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onTargetChanged, this);
        Ametys.message.MessageBus.on(Ametys.message.Message.WORKFLOW_CHANGED, this._onTargetChanged, this);
        Ametys.message.MessageBus.on(Ametys.message.Message.DELETED, this._onTargetDeleted, this);
    },
    
    /**
     * @private
     * Function to set the parent tool
     * @param {Object} parentTool The parent tool
     */
    setParentTool: function(parentTool)
    {
        this._parentTool = parentTool;
    },
    
    createPanel: function ()
    {
        return Ext.create('Ext.Component', {
            scrollable: true, 
            border: false,
            html : '',
            cls : 'details-view'
        });
    },
    
    refresh: function (manual)
    {
        let target = this.getCurrentSelectionTargets()[0];
        if (target != undefined)
        {
            this.showRefreshing();
            
            this._objectId = target.getParameters().id;
            
            let params = {objectId: this._objectId};
            
            Ametys.data.ServerComm.send({
                plugin: 'cms',
                url: 'properties.html',
                parameters: params, 
                priority: Ametys.data.ServerComm.PRIORITY_MAJOR, 
                callback: {
                    handler: this._updateTargetProperties,
                    scope: this,
                    arguments: [this._objectId]
                },
                responseType: 'html'
            });
        }
    },
    
    /**
     * @private
     * Callback function called after #refresh to update the target's properties
     * @param {HTMLElement} response The XML document.
     * @param {Array} args The callback arguments.
     */
    _updateTargetProperties: function (response, args)
    {
        let objectId = args[0];
        
        let currentSelectionTargets = this.getCurrentSelectionTargets();
        if (currentSelectionTargets == null || currentSelectionTargets.length == 0 || currentSelectionTargets[0].getParameters().id != objectId)
        {
            // too late => discard (another target has been selected)
            return;
        }
        
        if (Ametys.data.ServerComm.handleBadResponse("{{i18n UITOOL_DETAILS_ERROR}} '" + objectId + "'", response, 'Ametys.plugins.cms.properties.PropertiesTab'))
        {
            return;
        }
        
        this.getContentPanel().update(Ext.String.htmlDecode(response.getHTML()), true);
        
        let parentTool = Ametys.tool.ToolsManager.getTool(this._parentTool);
        parentTool.showTab(this.getWrapper());
        
        this.showRefreshed();
    },
    
    setNoSelectionMatchState: function (message, reason)
    {
        this.callParent(arguments);

        this._objectId = null;
        
        if (reason == Ametys.tool.SelectionTool.DeclineReason.MULTIPLE)
        {
            this.getContentPanel().update(message);
            
            let parentTool = Ametys.tool.ToolsManager.getTool(this._parentTool);
            parentTool.showTab(this.getWrapper());
        }
        else
        {
            this.getContentPanel().update('');
            
            let parentTool = Ametys.tool.ToolsManager.getTool(this._parentTool);
            parentTool.hideTab(this.getWrapper());
        }
    },
    
    /**
     * Listener on {@link Ametys.message.Message#WORKFLOW_CHANGED}, {@link Ametys.message.Message#MODIFIED} and {@link Ametys.message.Message#DELETED} messages. If the current
     * target is concerned, the tab will be out-of-date.
     * 
     * @param {Ametys.message.Message} message The bus message.
     * @protected
     */
    _onTargetChanged: function (message)
    {
        if (this.getTargetsInCurrentSelectionTargets(message).length > 0)
        {
            this.showOutOfDate();
        }
    },
    
    _onTargetDeleted: function (message)
    {
        if (this.getTargetsInCurrentSelectionTargets(message).length > 0)
        {
            this.setNoSelectionMatchState();
        }
    },
    
    isEmpty: function ()
    {
        return this.getContentPanel().html == '';
    }
});