/*
 *  Copyright 2017 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 UI helper provides a dialog to choose grouping fields for search export.
 * See #open method.
 */
Ext.define('Ametys.plugins.cms.search.ChooseSearchGroupingFields', {
    singleton: true,
    
    /**
     * @property {Function} _cbFn The call back function to call after group fields have been chosen.
     * @private
     */
    
    /**
     * Allow the user to select grouping fields
     * @param {Object} config The configuration options :
     * @param {String} [config.selectionMode="fixed"] The selection mode : 'fixed' to choose fields into a drop down or 'free' to choose field through a Code field with autocompletion
     * @param {Object[]} [config.fields] Array of available fields for grouping (each field should contains id and label). Required for 'fixed' selection mode
     * @param {Object[]} [config.codeMode] The mode to use for Code field. Only used for 'free' selection mode.
     * @param {String} [config.iconCls=ametysicon-file-extension-doc'] One or more CSS classes to apply to dialog's icon. Can be null to use the default one or use the icon instead.
     * @param {String} [config.icon] The full path to icon (16x16) for the dialog box. If null the iconCls will be used
     * @param {String} config.title The title of the dialog box.
     * @param {String} config.helpmessage The message displayed at the top of the dialog box.
     * @param {Function} config.callback The method that will be called when the dialog box is closed. Callback parameters are : 
     * @param {String} config.callback.groupFields The id of the group fields
     */
    open: function(config)
    {
        this._mode = config.selectionMode || 'fixed';
        this._cbFn = config.callback || Ext.emptyFn;
        this._createDialogBox(config.fields || [], config.icon, config.iconCls, config.title, config.helpmessage, config.codeMode);
        
        this._box.show();
        
        this._initForm(config);
    },
    
    /**
     * @private
     * Init form
     * @param {Object} config the configuration object
     */
    _initForm: function(config)
    {
        if (config.codeMode == 'solr-ametys-columns')
        {
            this._box.getComponent('groupFields').setContentTypes(config.contentTypes);
        }
    },
    
    /**
     * Creates the dialog box.
     * @param {Object[]} fields Array of available fields for grouping (each field should contains id and label). Required for 'fixed' selection mode
     * @param {String} icon The full path to icon (16x16 pixels) for the dialog box. Can be null to use CSS for icon
     * @param {String} iconCls One or more CSS classes to apply to dialog's icon. Can be null to use the default one or use the icon instead.
     * @param {String} title The title of the dialog box.
     * @param {String} helpmessage The message displayed at the top of the dialog box.
     * @param {Object[]} codeMode The mode to use for Code field. Only used for 'free' selection mode.
     * @private
     */
    _createDialogBox: function(fields, icon, iconCls, title, helpmessage, codeMode)
    {
        var groupFieldCfg = {
            itemId: 'groupFields',
            name: 'groupFields',
            width: '100%'
        }
        
        if (this._mode == 'fixed')
        {
            groupFieldCfg = Ext.apply(groupFieldCfg, {
                data: fields,
                xtype: 'orderable-tagfield',
                filterPickList: true,
                triggerOnClick: false,
                multiSelect: true,
                typeAhead: false
            });
        }
        else
        {
            groupFieldCfg = Ext.apply(groupFieldCfg, {
                xtype: 'solr-code',
                mode: codeMode,
                singleLine: true,
                height: 120,
                singleLine: true,
                cmParams: {
                    lineNumbers: false,
                    lineWrapping: true,
                    styleActiveLine: false,
                    extraKeys: {
                      'Ctrl-Space': 'autocomplete'
                    }
                }
            });
        }
        
        this._box = Ext.create('Ametys.window.DialogBox', {
            title: title || "{{i18n PLUGINS_CMS_UITOOL_SEARCH_GROUP_TITLE}}",
            icon: icon,
            iconCls: icon ? null : (iconCls || 'ametysicon-file-extension-doc'),
            
            width: 450,
            
            items: [{
                        xtype: 'component',
                        cls: 'a-text',
                        html: helpmessage || '{{i18n PLUGINS_CMS_UITOOL_SEARCH_GROUP_LABEL_DESC}}'
                    }, 
                    groupFieldCfg
            ],
            
            closeAction: 'destroy',
            
            referenceHolder: true,
            defaultButton: 'validate',
            
            buttons : [{
                reference: 'validate',
                text: "{{i18n PLUGINS_CMS_UITOOL_SEARCH_GROUP_OK}}",
                handler: Ext.bind(this._validate, this)
            }, {
                text: "{{i18n PLUGINS_CMS_UITOOL_SEARCH_GROUP_CANCEL}}",
                handler: Ext.bind(function() {this._box.close();}, this) // callback + hide
            }],
            
            listeners: {
                'show': function() {
                   this.updateLayout(); // Fix issue with code field
                }
            }
        });
    },
    
    /**
     * @private
     * Handler for 'ok' button
     * Calls the callback function passed in {@link #method-open} and hide the dialog box.
     */
    _validate: function()
    {
        var fields = [];
        var field = this._box.down('#groupFields');
        if (this._mode == 'fixed')
        {
            fields = field.getValue();
        }
        else
        {
            var values = field.getValue().split(',');
            Ext.Array.forEach(values, function(item)
            {
                fields.push(item.trim().replace(/\./g, '/'));//trim, and replace . with /
            });
        }
        
        this._cbFn(fields);
        this._box.close();
    }
});