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

/**
 * Field to select a profile
 */
Ext.define('Ametys.form.field.SelectProfile', {
    extend: 'Ext.form.field.ComboBox',
    
    /**
     * @cfg {String} [includeReader=true] Include the READER profile in the options
     */
    
    constructor:function(config)
    {
        Ext.apply(config, {
            valueField: 'id',
            displayField: 'label',
            store: {
                autoDestroy: true,
                proxy: {
                    type: 'ametys',
                    plugin: 'core',
                    url: 'rights/profiles.json',
                    extraParams: this._getProxyExtraParamsConfig(config),
                    reader: {
                        type: 'json',
                        rootProperty: 'profiles'
                    }
                },
                sorters: this._getSortersConfig(),
                fields: [
                    {name: 'id'},
                    {
                        name: 'label', 
                        type: 'string',
                        convert: function(value, record) 
                        {
                            // Escape HTML to prevent XSS
                            return Ext.String.escapeHtml(value);
                        }
                    }
                ]
            },
            
            autoLoadOnValue: true,
            editable: false
        });
        this.callParent(arguments);
    },
    
    _getSortersConfig: function()
    {
        return [{property: 'label', direction: 'ASC'}];
    },
    
    /**
     * @protected
     * Get the extra params used by the proxy
     * Overrides this method if you need to provide extra params
     * @returns the params
     */
    _getProxyExtraParamsConfig: function(config)
    {
        return {includeReader : config.includeReader != false};
    }
});