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

/**
 * This class provides a widget to select BUT training paths.
 * The available training paths are computed :
 * - from the field "mention" if it is used in a object who hold the mention (program)
 * - from the parent's program otherwise 
 *  
 */
Ext.define('Ametys.odf.widget.ParcoursBUT', {
    extend: 'Ametys.form.AbstractQueryableComboBox',
    
    /**
     * @cfg {String} [mentionFieldPath] The relative path of mention field.
     */
    
    /**
     * @property {String} _mentionFieldPath See #{cfg-mentionFieldPath}
     */
    
    valueField: 'id',
    displayField: 'title',
    
    initComponent: function()
    {
        this.multiple = this.multiple != false && this.multiple != 'false';
        this._mentionFieldPath = this.mentionFieldPath || null;
        
        this.callParent(arguments);
        
        if (this._mentionFieldPath && this.form && Ext.isFunction(this.form.onRelativeFieldsChange))
        {
            this.form.onRelativeFieldsChange([this._mentionFieldPath], this, this._updateComboboxValues);
        }
        else if (this.form)
        {
            // Initialize combobox values and disable state
            this.form.executeFormReady(this._updateComboboxValues, this);
        }
    },
    
    getStore: function()
    {
        var me = this;
        return Ext.create('Ext.data.Store', {
            proxy: {
                type: 'ametys',
                role: 'org.ametys.odf.enumeration.OdfReferenceTableHelper',
                methodName: 'getBUTParcoursItems',
                methodArguments: ['contentId', 'mentionId'],
                reader: {
                    type: 'json'
                }
            },
            fields: [
                {name: 'id'},
                {name: 'title'}
            ],
            
            sortOnLoad: true,
            sorters: [{property: 'title', direction:'ASC'}],
            
            listeners: {
                beforeload: {fn: this._onStoreBeforeLoad, scope: this},
                load: {fn: this._onStoreLoad, scope: this}
            }
        });
    },
    
    /**
     * Set the request parameters before loading the store.
     * @param {Ext.data.Store} store The store.
     * @param {Ext.data.operation.Operation} operation The Ext.data.Operation object that will be passed to the Proxy to load the Store.
     * @private
     */
    _onStoreBeforeLoad: function(store, operation)
    {
        var relativeFields = this.form.getRelativeFields([this._mentionFieldPath], this),
            mentionField = relativeFields[0];
        
        var mentionId = null;
        if (mentionField)
        {
            mentionId = mentionField.isExternalizableField ? (mentionField.getValue().status == 'local' ? mentionField.getValue().local : mentionField.getValue().external) : mentionField.getValue();
        }
        
        var params = operation.getParams() || {};
        operation.setParams(Ext.apply(params, {
            contentId: this.contentInfo.contentId,
            mentionId: mentionId
        }));
    },
    
    /**
     * @private
     */
    _onStoreLoad: function(store, records)
    {
        // disabled field when there is no available training paths (not part of a BUT diploma or mention empty)
        this.setDisabled(records.length == 0);
    },
    
    /**
     * Listener called when the value of a mention relative field changes
     * @private
     */
    _updateComboboxValues: function()
    {
        if (this.combobox)
        {
            this.combobox.getStore().load();
        }
    }
    
});