/*
 *  Copyright 2025 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 class provides a widget to select one or more contents.<br>
 * This contents come from the values of the content attribute path
 */
Ext.define('Ametys.cms.form.widget.SelectInContentAttributeValues', {
    extend: 'Ametys.form.widget.ComboBox',
    
    /**
     * @cfg {String} [contentId] The content id to get the attribute values. If null, we take the current selected content in message bus
     */
    contentId: null, 
    
    /**
     * @cfg {String} [attributePath] The attribute path to get values.
     */
    attributePath: null, 
    
    constructor: function (config)
    {
        config = Ext.apply(config, {
            queryMode: 'local',
            valueField : 'id',
            displayField : 'title'
        });
        
        this.callParent(arguments);
        
        if (!this.attributePath)
        {
            throw new Error("Widget parameter 'attributePath' is mandatory");
        }
        
        if (!this.contentId)
        {
            let targets = Ametys.message.MessageBus.getCurrentSelectionMessage().getTargets(Ametys.message.MessageTarget.CONTENT);
            if (targets.length)
            {
                this.contentId = targets[0].getParameters().id;
            }
        }
    },
    
    getStoreCfg: function(config)
    {
        return {
            proxy: {
                type: 'ametys',
                role: 'org.ametys.cms.content.ContentHelper',
                methodName: 'getContentDataAsJSON',
                methodArguments: ['contentId', 'attributePath'],
                reader: {
                    type: 'json',
                    rootProperty: "data"
                }
            },
            autoLoad: true, 
            sorters: [{property: config.displayField, direction: 'ASC'}],
            listeners: {
                scope: this,
                beforeload: function(store, operation)
                {
                    var params = operation.getParams() || {};
                    operation.setParams(Ext.apply(params, {
                        contentId: this.contentId,
                        attributePath: this.attributePath
                    }));
                }
            }
        };
    }
});