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

/**
 * Combobox showing all catalogs (to be used with a CatalogEnumerator).
 * The value can be set with the "CURRENT" string to use the catalog defined as default catalog.
 */
Ext.define('Ametys.odf.widget.SelectCatalog', {
    extend: 'Ametys.form.widget.ComboBox',
    
    setValue: function(value)
    {
        
        if (value == 'CURRENT')
        {
            try
            {
                Ametys.odf.catalog.CatalogDAO.getDefaultCatalogName(
                    [],
                    function(catalogName) {
                        // test again, the default value is set when the field is opened, then the real value is set and it can be done BEFORE the callback
                        if (this.value == 'CURRENT' || this.value == null)
                        {
                            Ametys.form.widget.ComboBox.prototype.setValue.apply(this, [catalogName]);
                        }
                    },
                    { scope: this }
                );
            }
            catch (e)
            {
                // If there is a problem with CatalogDAO (like dependencies in some environments)
                value = null;
            }
        }
        
        this.callParent([value]);
    },
    
    getStoreCfg: function(config)
    {
        if (!config.enumeration && !config.proxyStore)
        {
            config.proxyStore = {
                type: 'ametys',
                role: 'org.ametys.odf.catalog.CatalogDAO',
                methodName: 'getCatalogs',
                methodArguments: []
            }
            config.autoLoad = true;
        }
        return this.callParent(arguments);
    }    
});