/*
 *  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 depending on a catalog.<br>
 * This embeds a drop down list with querying on title of contents and type-ahead support.<br> 
 * Advanced search through a dialog box could be enable. See #cfg-allowSearch.<br>
 * Allow content creation using #cfg-allowCreation.<br>
 * 
 * This widget allow to provide a catalog, to limit the items to select to this given catalog
 * The catalog can be provided directly by its identifier, or by a relative path of form catalog field
 * 
 * This widget is intended for use in search form. In edition, such behaviour is supported by
 * Ametys.odf.widget.SelectProgramItemOfSameContext that rely only of the identifier of the content
 * and doesn't require the presence of a catalog field
 */
Ext.define('Ametys.odf.widget.SelectCatalogAwareContent', {
    extend: 'Ametys.cms.form.widget.SelectContent',
    
    /**
     * @cfg {String} [catalog] The identifier of the catalog to allow search on
     */
    /**
     * @property {String} _catalog The identifier of the catalog to allow search on. See #cfg-catalog
     * @private
     */
    
    /**
     * @cfg {String} [catalogField] The relative path of form catalog field. 
     */
    /**
     * @property {String} _catalogField The relative path of form catalog field. See #cfg-catalogField
     * @private
     */
    
    /**
     * @cfg {String} [targetCatalogCriteria="reference-catalog-eq"] The name of the catalog criteria on targetted search model 
     */
    /**
     * @property {String} _targetCatalogCriteria The name of the catalog criteria on targetted search model. See #cfg-targetCatalogCriteria
     * @private
     */
    
    constructor: function(config) 
    {
        this.callParent(arguments);

        if (config.catalog)
        {
            this._catalog = config.catalog;
        }
        
        if (config.catalogField)
        {
            this._catalogField = config.catalogField;
            Ametys.form.Widget.onRelativeValueChange(this._catalogField, this, this._onCatalogValueChange, this);
        }
        
        this._targetCatalogCriteria = config.targetCatalogCriteria || 'reference-catalog-eq';
    },
    
    _onCatalogValueChange: function(relativePath, data, newValue, oldValue)
    {
        let contentIds = this.multiple
            ? this.getValue()
            : this.getValue()
                ? [this.getValue()]
                : [];
        if (contentIds.length > 0 && contentIds[0] !== this._noValueOptionId)
        {
            // Get the catalog of one of the selected values
            Ametys.data.ServerComm.callMethod({
                role: "org.ametys.odf.catalog.CatalogsManager",
                methodName: "getContentCatalog",
                parameters: [contentIds[0]],
                callback: {
                    handler: this._onCatalogValueChangeCb,
                    scope: this,
                    arguments: [relativePath, data, newValue, oldValue]
                },
                waitMessage: true
            });
        }

        // Delete lastQuery to force load of store next time the combo is expanded
        delete this.combobox.lastQuery;
    },

    _onCatalogValueChangeCb: function(catalogName, args)
    {
        let newValue = args[2];
        let oldValue = args[3];
        if (newValue != oldValue && catalogName != newValue)
        {
            // Remove current value -> the selected content is no the selected catalog anymore
            this.reset();
        }
    },
    
    _getAdditionalLoadValues: function()
    {
        var values = this.callParent(arguments);
        
        let catalogValue = this._getCatalog();
        if (catalogValue)
        { 
            values[this._targetCatalogCriteria] = catalogValue;
        }
        
        return values;
    },
    
    /**
     * Retrieves the catalog from the given identifier
     * @private
     */
    _getCatalog: function ()
    {
        return  this._catalog || (this._catalogField ? Ametys.form.Widget.getRelativeValue(this._catalogField, this) : null);
    }
})