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

/**
 * This class provides a widget to select one or more contents from a enumeration.<br>
 * This widget is the default widget registered for fields of type Ametys.form.WidgetManager#TYPE_CONTENT with a enumeration.<br>
 */
Ext.define('Ametys.cms.form.widget.SelectContentWithEnumeration', {
    extend: 'Ametys.form.widget.ComboBox',
    
    convertEnumerationValue: function(value)
    {
        return this._getId(value);
    },

    setValue: function(value)
    {
        var ids = this._getIds(value);
        
        this.callParent([this.multiple ? ids : (ids.length > 0 ? ids[0] : null)]);
    },
    
    
    /**
     * @private
     * Get the ids of content from the values selected
     * @param {Object} The values
     */
    _getIds: function(values)
    {
        var ids = [];
        
        if (values)
        {
            values = Ext.Array.from(values);
            var me = this;
            Ext.Array.each(values, function(v) {
                var id = me._getId(v);
                ids.push(id);
            })
        }
        return ids;
    },
    
    /**
     * @private
     * Get the id of content from the given value
     * @param {Object} The value
     * @return {String} the content id
     */
    _getId: function(value)
    {
        if (Ext.isObject(value) && value.id)
        {
            return value.id;
        }   
        else
        {
            return value;
        }
    }
});