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

/**
 * Select a educational path
 */
Ext.define('Ametys.odf.widget.SelectEducationalPath', {
    extend: 'Ametys.form.AbstractQueryableComboBox',
    
    valueField: 'id',
    displayField: 'title',
    
    constructor: function (config)
    {
        this.updateAdditionalWidgetsConf(config);
        this.callParent(arguments);
    },
    
    updateAdditionalWidgetsConf: function(config)
    {
        this._contentId = config.contentId || config.contentInfo && config.contentInfo.contentId;
    },
    
    getStore: function()
    {
        if (!Ext.data.schema.Schema.get('default').hasEntity('Ametys.odf.widget.EducationalPath')) {
            Ext.define("Ametys.odf.widget.EducationalPath", {
                extend: 'Ext.data.Model',

                idProperty: 'id',

                fields: [
                         {name: 'id', type: 'string'},
                         {name: 'title', type: 'string'}
                ]
            });
        }
        
        return Ext.create('Ext.data.Store', {
            model: 'Ametys.odf.widget.EducationalPath',
            proxy: {
                type: 'ametys',
                methodName: 'getEducationalPathsEnumeration',
	            methodArguments: ['programItemId'],
	            role: 'org.ametys.odf.ODFHelper',
	            reader: {
	                type: 'json'
	            }
            },
            
            sorters: [{property: 'title', direction:'ASC'}],
            
            listeners: {
                beforeload: {fn: this._onStoreBeforeLoad, 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 params = operation.getParams() || {};
        operation.setParams(Ext.apply(params, {
            programItemId: this._contentId
        }));
    },
    
    /**
     * Set the value after the store load
     * @param {Ext.data.Store} store The store.
     * @param {Ext.data.Model[]} records The loaded records.
     * @param {Boolean} successful True if the operation was successful.
     * @param {Ext.data.operation.Operation} The operation object used by proxy
     * @private
     */
    _onStoreLoad: function(store, records, successful, operation)
    {
        if (operation.aborted)
        {
            // the load has been canceled. Do nothing.
            return;
        }
        
        var value = this.getValue(),
            store = this.getStore();
                
        if (store.find(this.valueField, value) != -1)
        {
            this.setValue(value);
        }
        else if (store.find(this.valueField, this.defaultValue) != -1)
        {
            this.setValue(this.defaultValue);
        }
        else
        {
            this.reset();
        }
    },
    
    getLabelTpl: function ()
    {
        return '{[values.title]}';
    }
    
});