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

/**
 * Field that displays a code editor supporting solr autocompletion
 * Requires CodeMirror (version 3.14) to be loaded.
 * See http://codemirror.net/ to have documentation on it.
 */
Ext.define('Ametys.form.field.SolrCode', {
    extend: 'Ametys.form.field.Code',
    alias: ['widget.solr-code'],
    
    /**
     * @property {String/String[]} ctypes the list of content type id to use for autocompletion
     */
    constructor: function (config)
    {
        config.cmParams = config.cmParams || {};
        config.cmParams.hintOptions = config.cmParams.hintOptions || {};
        config.cmParams.extraKeys = config.cmParams.extraKeys || {};
        
        config.cmParams = Ext.applyIf(config.cmParams, {
            lineNumbers: false,
            lineWrapping: true,
            styleActiveLine: false
        });
        config.cmParams.extraKeys = Ext.apply(config.cmParams.extraKeys, {
            'Ctrl-Space': 'autocomplete'
        });
        config.cmParams.hintOptions = Ext.apply(config.cmParams.hintOptions, {
            ctypes: Ext.Array.from(config.ctypes)
        });
        
        this.callParent(arguments);
    },
    /**
     * Set the content types id to use for autocompletion
     * @param {String[]} ctypes the list of content type id
     */ 
    setContentTypes : function(ctypes)
    {
        var me = this;
        ctypes = ctypes || [];
        if (ctypes.length > 1)
        {
            ctypes = Ametys.cms.content.ContentTypeDAO.getCommonAncestors(ctypes);
        }
        
        let cm = me.getCM();
        if (cm)
        {
            let hintOptions = cm.getOption("hintOptions");
            hintOptions.ctypes = ctypes;
            me.getCM().setOption("hintOptions", hintOptions);
        }
        else
        {
        	this.getInitialConfig("cmParams").hintOptions.ctypes = ctypes;
        }
    }
});