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

/**
 * Listener for the ODF root page major changes. Fires a major modified message on the ODF root to refresh the sitemap.
 */
Ext.define('Ametys.plugins.odf.web.root.ODFRootListener', {
   
    singleton: true,
    
    constructor: function()
    {
        Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onModified, this);
        Ametys.message.MessageBus.on(Ametys.message.Message.DELETED, this._onModified, this);
    },
   
    /**
     * Listener handler for modified or deleted messages
     * @param {Ametys.message.Message} message the message
     */
	_onModified: function(message)
	{ 
	   var target = message.getTarget(Ametys.message.MessageTarget.CONTENT);
       if (target != null && (Ext.Array.contains(target.getParameters().types, "org.ametys.plugins.odf.Content.program") || Ext.Array.contains(target.getParameters().types, "org.ametys.plugins.odf.Content.subProgram")))
       {
            Ametys.data.ServerComm.callMethod({
                role: "org.ametys.plugins.odfweb.repository.OdfPageHandler", 
                methodName: "getOdfRootPageIds", 
                parameters: [Ametys.getAppParameter("siteName"), target.getParameters().lang],
                callback: [
                    {
                        handler: this._getRootPagesCb,
                        scope: this
                    }
                ],
                waitMessage: false,
                errorMessage: false
            });
        }
    },
    
    /**
     * @private
     * Callback function invoked after retrieving the ODF root pages.<br/>
     * Send a major modification to the ODF root pages, if exist.
     * @param {String} pageIds The id of ODF root pages
     */
    _getRootPagesCb: function(pageIds)
    {
        if (pageIds && pageIds.length > 0)
        {
            Ext.create("Ametys.message.Message", {
	            type: Ametys.message.Message.MODIFIED,
	            parameters: {
	                major: true
	            },
	            targets: {
                    id: Ametys.message.MessageTarget.PAGE,
                    parameters: {ids: pageIds}
	            }
	        });
        }
    }
   
});