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

/**
 * Singleton class helper for query extraction components edition.
 * @private
 */
 Ext.define('Ametys.plugins.extraction.edition.EditQueryExtractionComponentDialog', {
    extend: "Ametys.plugins.extraction.edition.EditGroupExtractionComponentDialog",
    singleton: true,
    
    /**
     * @protected
     * Retrieve the dialog title
     * @return {String} the dialog title
     */
    _getDialogTitle: function ()
    {
        if (this._mode == 'new')
        {
            return "{{i18n PLUGINS_EXTRACTION_ADD_QUERY_DIALOG_TITLE}}";
        }
        return "{{i18n PLUGINS_EXTRACTION_EDIT_QUERY_DIALOG_TITLE}}";
    },
    
    /**
     * @protected
     * Retrieve the dialog icon class
     * @return {String} the dialog icon class
     */
    _getDialogIconCls: function ()
    {
        return "ametysicon-query-search";
    },
    
    /**
     * @protected
     * Retrieves the form configuration elements
     * @param {Object} response needed information to configure form
     * @return {Object} the form configuration element
     */
    _getFormConfiguration: function(response)
    {
        var configuration = {};
        
        // Tag name field
        Ext.apply(configuration, this._getTagNameFormConfiguration());
        
        // Clauses field
        Ext.apply(configuration, this._getClausesFormConfiguration());
        
        // Grouping fields
        Ext.apply(configuration, this._getGroupingFieldsFormConfiguration());
        
        // Query type and content types or saved query field
        Ext.apply(configuration, this._getQueryTypeFormConfiguration());
        
        // Init columns and sort inputs widget parameters
        var columnsAndSortsWidgetParams = {};
        Ext.apply(columnsAndSortsWidgetParams, this._codeWidgetParams);
        Ext.apply(columnsAndSortsWidgetParams, {height: 44, mode: 'solr-ametys-columns'});
        
        // Columns field for empty query
        configuration.emptyQueryColumns = {
            type: 'string',
            label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_COLUMNS_LABEL}}",
            description: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_COLUMNS_DESCRIPTION}}",
            disableCondition: {
                condition: [{
                    id: 'queryType',
                    operator: 'neq',
                    value: 'empty'
                }]
            },
            widget: 'edition.solr-code',
            'widget-params': columnsAndSortsWidgetParams
        };
        
        // Sorts field for empty query
        configuration.emptyQuerySorts = {
            type: 'string',
            label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_SORTS_LABEL}}",
            description: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_SORTS_DESCRIPTION}}",
            validation: {
                regexp: '^\\w[\\w-\\.]*(\\s*\\((ASC|asc|desc|DESC)\\))?(\\s*,\\s*\\w[\\w-\\.]*(\\s*\\((ASC|asc|desc|DESC)\\))?)*$',
                regexText: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_SORTS_REGEX_TEXT}}"
            },
            disableCondition: {
                condition: [{
                    id: 'queryType',
                    operator: 'neq',
                    value: 'empty'
                }]
            },
            widget: 'edition.solr-code',
            'widget-params': columnsAndSortsWidgetParams
        };
        
        // Override columns field
        configuration.overrideColumns = {
            type: 'string',
            label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_OVERRIDE_COLUMNS_LABEL}}",
            description: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_OVERRIDE_COLUMNS_DESCRIPTION}}",
            enumeration: [{
                value: 'only-ref',
                label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_OVERRIDE_COLUMNS_USE_ONLY_REF_LABEL}}"
            },
            {
                value: 'add',
                label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_OVERRIDE_COLUMNS_ADD_TO_REF_LABEL}}"
            },
            {
                value: 'override',
                label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_OVERRIDE_COLUMNS_OVERRIDE_REF_LABEL}}"
            }],
            disableCondition: {
                condition: [{
                    id: 'queryType',
                    operator: 'neq',
                    value: 'ref'
                }]
            },
            validation: {
                mandatory: true
            }
        };
        
        // Columns field for ref query
        configuration.refQueryColumns = {
            type: 'string',
            label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_COLUMNS_LABEL}}",
            description: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_COLUMNS_DESCRIPTION}}",
            // TODO EXTRACT-XX hide field if override columns is not set to add or override
            disableCondition: {
                condition: [{
                    id: 'queryType',
                    operator: 'neq',
                    value: 'ref'
                }]
            },
            widget: 'edition.solr-code',
            'widget-params': columnsAndSortsWidgetParams
        };
        
        // Override sorts field
        configuration.overrideSorts = {
            type: 'string',
            label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_OVERRIDE_SORTS_LABEL}}",
            description: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_OVERRIDE_SORTS_DESCRIPTION}}",
            enumeration: [{
                value: 'only-ref',
                label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_OVERRIDE_SORTS_USE_ONLY_REF_LABEL}}"
            },
            {
                value: 'add',
                label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_OVERRIDE_SORTS_ADD_TO_REF_LABEL}}"
            },
            {
                value: 'override',
                label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_OVERRIDE_SORTS_OVERRIDE_REF_LABEL}}"
            }],
            disableCondition: {
                condition: [{
                    id: 'queryType',
                    operator: 'neq',
                    value: 'ref'
                }]
            },
            validation: {
                mandatory: true
            }
        };
        
        // Sorts field for ref query
        configuration.refQuerySorts = {
            type: 'string',
            label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_SORTS_LABEL}}",
            description: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_SORTS_DESCRIPTION}}",
            validation: {
                regexp: '^\\w[\\w-\\.]*(\\s*\\((ASC|asc|desc|DESC)\\))?(\\s*,\\s*\\w[\\w-\\.]*(\\s*\\((ASC|asc|desc|DESC)\\))?)*$',
                regexText: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_SORTS_REGEX_TEXT}}"
            },
            // TODO EXTRACT-XX hide field if override sorts is not set to add or override
            disableCondition: {
                condition: [{
                    id: 'queryType',
                    operator: 'neq',
                    value: 'ref'
                }]
            },
            widget: 'edition.solr-code',
            'widget-params': columnsAndSortsWidgetParams
        };
        
        return configuration;
    },
    
    _getInitFormCreationValues: function()
    {
        var fromParent = this.callParent(arguments);
        var values = fromParent.values;
        var repeaters = fromParent.repeaters;
    
        return {
            values: values,
            repeaters: repeaters
        };
    },
    
    /**
     * @protected
     * Retrieves the values to set to init form on edition mode
     * @return {Object} the values to set to init form
     */
    _getInitFormEditionValues: function()
    {
        var fromParent = this.callParent(arguments);
        var values = fromParent.values;
        var repeaters = fromParent.repeaters;
        
        if (this._data.useQueryRef)
        {
            if (this._data.overrideColumns)
            {
                values.overrideColumns = 'override';
                values.refQueryColumns = this._data.columns;
            }
            else if (Ext.isEmpty(this._data.columns))
            {
                values.overrideColumns = 'only-ref';
            }
            else
            {
                values.overrideColumns = 'add';
                values.refQueryColumns = this._data.columns;
            }
            
            if (this._data.overrideSorts)
            {
                values.overrideSorts = 'override';
                values.refQuerySorts = this._data.sorts;
            }
            else if (Ext.isEmpty(this._data.sorts))
            {
                values.overrideSorts = 'only-ref';
            }
            else
            {
                values.overrideSorts = 'add';
                values.refQuerySorts = this._data.sorts;
            }
        }
        else
        {
            values.emptyQueryColumns = this._data.columns;
            values.emptyQuerySorts = this._data.sorts;
        }
        
        return {
            values: values,
            repeaters: repeaters
        };
    },
    
    /**
     * @private
     * Gets the values of the form
     * @return {Object} The form values
     */
    _getFormValues: function()
    {
        var values = this.callParent(arguments);
        
        var keys = Ext.Object.getKeys(values);
        var resultKeys = Ext.Array.filter(keys, function(key) {
            return key != "queryType"
                && key != "emptyQueryColumns" && key != "overrideColumns" && key != "refQueryColumns"
                && key != "emptyQuerySorts" && key != "overrideSorts" && key != "refQuerySorts";
        }, this);
        
        // copy values except clauses repeaters keys and add clauses and clauses variables
        var result = Ext.copy({}, values, resultKeys);
        
        var columns = [];
        switch (values.queryType)
        {
            case 'ref':
                result.useQueryRef = true;
                result.overrideColumns = values.overrideColumns == 'override';
                result.columns = values.refQueryColumns;
                result.overrideSorts = values.overrideSorts == 'override';
                result.sorts = values.refQuerySorts;
                break;
            case 'empty':
            default:
                result.useQueryRef = false;
                result.columns = values.emptyQueryColumns;
                result.sorts = values.emptyQuerySorts;
                break;
        }
        
        return result;
    }
 });