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

/**
 * Class defining the rules tool for container content
 */
Ext.define('Ametys.plugins.odf.pilotage.tool.RulesTool', {
    extend: "Ametys.tool.SelectionTool",
    
    /**
     * @private
     * @property {String} _containerId The id of the container.
     */
     
    /**
     * @private
     * @property {String} _containerTitle The title of the container.
     */
      
     /**
     * @private
     * @property {String} _thematicId The id of the thematic.
     */
     
     /**
     * @private
     * @property {String} _thematicType The type of the thematic.
     */
     
     /**
     * @private
     * @property {String} _ruleId The id of the rule.
     */
     
     /**
     * @private
     * @property {Boolean} _ruleDerogable True if the selected rule is derogable.
     */
     
     /**
     * @private
     * @property {Boolean} _ruleDerogated True if the selected rule is derogated.
     */
    
    /**
     * @private
     * @property {String} _ruleType The type of the rule.
     */
     
    constructor: function(config)
    {
        this.callParent(arguments);
        
        Ametys.message.MessageBus.on(Ametys.message.Message.SELECTION_CHANGED, this._onMessageSelectionChanged, this);
        Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onMessageModified, this);
        
    },
    
    createPanel: function()
    {
        this.setIconDecorator(null);
        
        this._iframe = Ext.create("Ext.ux.IFrame", {}); 
        this._iframe.on ('load', this._onIframeLoad, this);
                
        return Ext.create('Ext.Panel', { 
            cls: 'thematics-preview-tool',
            border: false,
            layout: 'border',
            scrollable: false,
            
            items: [
                this._iframe
            ]
        });
    },
    
    /**
     * @private
     * Listener called when the iframe is loaded.
     * Protects the iframe by handling links of the internal frame by setting a onclick on every one
     * @param {Ext.ux.IFrame} iframe The iframe
     */    
    _onIframeLoad: function (iframe)
    {
        if (window.event && window.event.srcElement.readyState && !/loaded|complete/.test(window.event.srcElement.readyState))
        {
            return;
        }
        
        try
        {
            this._iframe.getWin().onfocus = Ext.bind(this._onIframeFocus, this);
        }
        catch (e)
        {
            // ignore
        }
    },    
        
    /**
     * @private
     * Listener when iframe takes the focus.<br/>
     * Force the focus on tool.
     */
    _onIframeFocus: function ()
    {
        // Force focus on tool
        this.focus();
    },
    
    sendCurrentSelection: function()
    {
        var contentTarget = {
            id: Ametys.message.MessageTarget.CONTENT,
            parameters: {
                ids: [this._containerId]
            }
        };
        
        if (this._thematicId)
        {
            var thematicTarget = {
                id: Ametys.message.MessageTarget.THEMATIC,
                parameters: {
                    id: this._thematicId,
                    type: this._thematicType
                }
            };
            
            if (this._ruleId)
            {
                var ruleTarget = {
                    id: Ametys.message.MessageTarget.RULE,
                    parameters: {
                        id: this._ruleId,
                        derogable: this._ruleDerogable,
                        derogated: this._ruleDerogated,
                        type: this._ruleType
                    }
                };
                
                thematicTarget.subtargets = ruleTarget;
            }
            
            contentTarget.subtargets = thematicTarget;
        }
        
        Ext.create("Ametys.message.Message", {
            type: Ametys.message.Message.SELECTION_CHANGED,
            targets: [contentTarget]
        });
    },
    
    setParams: function(params)
    {
        this.callParent(arguments);
        
        this._containerId = params.id;
        this._containerTitle = params.title;
        this.refresh();
    },
    
    refresh: function()
    {
        this.setTitle("{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_RULES_TOOL_PREFIX}} - " + this._containerTitle);
        this.showRefreshing();
        
        var args = '?programItem=' + encodeURIComponent(this._containerId);
        if (this._thematicId)
        {
            args += '&thematicId=' + encodeURIComponent(this._thematicId);
            if (this._ruleId)
            {
                args += '&ruleId=' + encodeURIComponent(this._ruleId);
            }
        }
        
        var appParameters = Ametys.getAppParameters();
        Ext.Object.each(appParameters, function(key, value) {
            args += '&' + key + '=' + encodeURIComponent(value);
        });
        
        this._iframe.load(Ametys.CONTEXT_PATH + '/plugins/odf-pilotage/container-rules.html' + args)
        this.showRefreshed();
    },
    
    getMBSelectionInteraction: function()
    {
        return Ametys.tool.Tool.MB_TYPE_ACTIVE;
    },
    
    /**
     * Listener on selection changed message.
     * @param {Ametys.message.Message} message The selection changed message.
     * @private
     */
    _onMessageSelectionChanged: function(message)
    {
        var thematicTarget = message.getTarget(Ametys.message.MessageTarget.THEMATIC);
        if (thematicTarget)
        {
            this._thematicId = thematicTarget.getParameters().id;
            this._thematicType = thematicTarget.getParameters().type;
            var ruleTarget = message.getTarget(Ametys.message.MessageTarget.RULE);
            if (ruleTarget)
            {
                this._ruleId = ruleTarget.getParameters().id;
                this._ruleDerogable = ruleTarget.getParameters().derogable;
                this._ruleDerogated = ruleTarget.getParameters().derogated;
                this._ruleType = ruleTarget.getParameters().type;
            }
        }
    },
    
    /**
     * Listener on modified content message.
     * @param {Ametys.message.Message} message The modified content message.
     * @private
     */
    _onMessageModified: function(message)
    {
        var contentTarget = message.getTarget(Ametys.message.MessageTarget.CONTENT);
        if (contentTarget && contentTarget.getParameters().id == this._containerId)
        {
            this._onMessageSelectionChanged(message);
            this.sendCurrentSelection();
            this.refresh();
        }
    }
});

/** Class defining target message names for thematics and rules */
Ext.define("Ametys.message.ThematicMessageTarget",
{
    override: "Ametys.message.MessageTarget",
    
    statics: 
    {
        /**
         * @member Ametys.message.MessageTarget
         * @readonly
         * @property {String} THEMATIC The target type is a thematic. The expected parameters are:  
         * @property {String} THEMATIC.id The code of the thematic
         * @property {String} THEMATIC.type The type of the thematic
         */
        THEMATIC: "thematic",
        
        /**
         * @member Ametys.message.MessageTarget
         * @readonly
         * @property {String} RULE The target type is an rule. The expected parameters are:  
         * @property {String} RULE.id The code of the rule
         * @property {String} RULE.type The type of the rule
         * @property {Boolean} RULE.derogable If the rule is derogable
         * @property {Boolean} RULE.derogated If the rule is derogated
         */
        RULE: "rule"
    }
});