/*
 *  Copyright 2022 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 displaying a combobox allowing to select one of the values from a given enumerator.
 * 
 * Enumeration are already supported by the "Ametys.form.widget.ComboBox".
 * This widget is only relevant for config element definition that require access
 * to the service manager in order to enumerate their entries
 */
Ext.define('Ametys.form.widget.EnumeratorCombobox', {
    extend: "Ametys.form.widget.ComboBox",
    
	/**
	 * @cfg {String} enumerator-role (required) The role of enumerator holding entries
	 */
    /**
     * @cfg {String} [emptyValueIsNull=true] When no value is selected in non-multiple mode, the value will be null or empty string.
     */
    emptyValueIsNull: true,
	
	/**
     * @cfg {String} [serverRole=org.ametys.plugins.core.ui.util.ParameterEnumeratorHelper] The role of server component to get enumerator entries
     */
	/**
     * @cfg {String} [methodName=getEntries] The "callable" method to get enumerator entries
     */
    
    constructor: function (config)
    {
        config = Ext.apply(config, {
            queryMode: 'local',
            valueField: 'id',
            displayField: 'label',
            regex: undefined // The enumerator combobox can be used as an alternative to textfield when not in safemode. The regexp configuration of the textfield is not relevant here (and will create issues)
        });
		
		config = Ext.applyIf(config, {
			serverRole: 'org.ametys.plugins.core.ui.util.ParameterEnumeratorHelper',
			methodName: 'getEntries'
        });
        
        config.listConfig = Ext.applyIf(config.listConfig || {}, {
            getInnerTpl: function(displayField) {
                return '{[Ext.String.escapeHtml(values.' + displayField + ')]}';
            }
        });
        
        this.callParent(arguments);
    },
    
    onAdded: function()
    {
        this.callParent(arguments);
        
        if (this.getInitialConfig().depends)
        {
            for (let s of this.getInitialConfig().depends.split(","))
            {
                Ametys.form.Widget.onRelativeValueChange(s.trim(), this, this._reset, this);
            }
        }
    },
    
    _reset: function()
    {
        let me = this;
        this.getStore().reload({ callback: function() {
            me.validate();
        }});
    },
    
    getStoreCfg: function(config)
    {
        let parameters = ['role'];
        if (config.depends)
        {
            parameters.push("contextualParameters"); 
        }
        
        return {
            proxy: {
                type: 'ametys',
                role: config.serverRole,
                methodName: config.methodName,
                methodArguments: parameters,
                reader: {
                    type: 'json',
                    rootProperty: "data"
                }
            },
            autoLoad: true, 
            sorters: [{property: config.displayField, direction: 'ASC'}],
            listeners: {
                scope: this,
                'beforeload': function(store, operation)
                {
                    // Get the parameters, or create empty object if needed
                    var parameters = operation.getParams() || {};
                    // Add the enumerator role to the parameters
                    let map = {role: config["enumerator-role"]};
                    
                    // Add other depedencies
                    if (config.depends)
                    {
                        let dependencies = [];
                        
                        for (let s of config.depends.split(","))
                        {
                            dependencies.push(Ametys.form.Widget.getRelativeValue(s.trim(), this)); 
                        }
                        
                        map.contextualParameters = {dependencies: dependencies};
                    }
                    
                    params = Ext.apply(parameters, map);
                    
                    // Set the parameters
                    operation.setParams(parameters);
                }
            }
        };
    },
    
    getValue: function()
    {
        let v = this.callParent(arguments);
        if (v === null && (this.emptyValueIsNull === false || this.emptyValueIsNull === "false"))
        {
            return "";
        }
        else
        {
            return v;
        }
    }
});