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

/**
 * Convert a sitemap or page MessageTarget into right context.
 * 
 * In case of a page target, if the page include a 'zoneitem-id' param,
 * if the zoneitem is a content, the returned context will be this content
 * allowing inspection of the subtarget.
 */
Ext.define('Ametys.plugins.web.rights.SitemapElementTargetToContextConvertor', {
    extend: 'Ametys.plugins.coreui.rights.AbstractTargetToContextConvertor',
    
    isSupportedTarget: function(target)
    {
        return target != null &&
            (target.getId() == Ametys.message.MessageTarget.PAGE
            || target.getId() == Ametys.message.MessageTarget.SITEMAP);
    },
    
    areSameTargets: function(target1, target2)
    {
        // Should never be called with a sitemap parameter.
        // Even if it happens, this will works
        return this.callParent(arguments) && target1.getParameters()['zoneitem-id'] == target2.getParameters()['zoneitem-id'];
    },
    
    convert: function(target, parameters)
    {
        if (target.getId() == Ametys.message.MessageTarget.PAGE && target.getParameters()['zoneitem-id'] != null)
        {
            // check if current zone item is a content
            var sub = target.getSubtarget(t => t.getId() == Ametys.message.MessageTarget.CONTENT);
            return (sub || target).getParameters().id;
        }
        else
        {
            return target.getParameters().id;
        }
    },
    
    getContextInfo:function(target, parameters)
    {
        if (target.getId() == Ametys.message.MessageTarget.SITEMAP)
        {
            return {label: target.getParameters().name, type: `{{i18n PLUGINS_WEB_SITEMAP_ELEMENT_TARGET_CONVERTOR_SITEMAP_TYPE_LABEL}}`}
        }
        else if (target.getParameters()['zoneitem-id'] != null)
        {
            // check if current zone item is a content
            var sub = target.getSubtarget(t => t.getId() == Ametys.message.MessageTarget.CONTENT);
            if (sub)
            {
                return {label: sub.getParameters().title, type: '{{i18n plugin.cms:PLUGINS_CMS_CONTENT_TARGET_CONVERTOR_TYPE_LABEL}}'};
            }
        }
        
        return {label: target.getParameters().title, type: '{{i18n PLUGINS_WEB_SITEMAP_ELEMENT_TARGET_CONVERTOR_PAGE_TYPE_LABEL}}'};
    }
});