/*
 *  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 clauses variables node edition.
 * @private
 */
 Ext.define('Ametys.plugins.extraction.edition.EditClausesVariablesNodeDialog', {
    extend: "Ametys.plugins.extraction.edition.EditExtractionNodeDialog",
    singleton: true,
    
    /**
     * @protected
     * Retrieve the dialog title
     * @return {String} the dialog title
     */
    _getDialogTitle: function ()
    {
        return "{{i18n PLUGINS_EXTRACTION_EDIT_CLAUSES_VARIABLES_DIALOG_TITLE}}";
    },
    
    /**
     * @protected
     * Retrieve the dialog icon class
     * @return {String} the dialog icon class
     */
    _getDialogIconCls: function ()
    {
        return "ametysicon-symbol-x";
    },
    
    /**
     * @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 = {};
        
        // Enumerations
        var typeEnumeration = [];
        
        // Content dropdown
        typeEnumeration.push({label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_CLAUSES_VARIABLE_TYPE_ENUM_SELECT_CONTENTS}}", value: 'selectContents'});
        // Solr Request
        typeEnumeration.push({label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_CLAUSES_VARIABLE_TYPE_ENUM_SOLR_REQUEST}}", value: 'solrRequest'});
        
        // Repeater for variables
        var composition = {};
        configuration.variables = {
            name: 'variables',
            type: 'repeater',
            label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_CLAUSES_VARIABLE_REPEATER_LABEL}}",
            description: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_CLAUSES_VARIABLE_REPEATER_DESCRIPTION}}",
            'add-label': "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_CLAUSES_VARIABLE_REPEATER_ADD_LABEL}}",
            'del-label': "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_CLAUSES_VARIABLE_REPEATER_DELETE_LABEL}}",
            'min-size': 0,
            elements: composition
        };
        
        // single variable name field
        composition.name = {
            type: 'string',
            label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_CLAUSES_VARIABLE_NAME_INPUT_LABEL}}",
            description: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_CLAUSES_VARIABLE_NAME_INPUT_DESCRIPTION}}",
            validation: {
                mandatory: true,
                regexp: '^[a-zA-Z_-][a-zA-Z0-9_-]*$',
                regexText: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_CLAUSES_VARIABLE_NAME_INPUT_REGEX_TEXT}}"
            }
        };
        
        // single variable type field
        composition.type = {
            type: 'string',
            label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_CLAUSES_VARIABLE_TYPE_INPUT_LABEL}}",
            description: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_CLAUSES_VARIABLE_TYPE_INPUT_DESCRIPTION}}",
            enumeration: typeEnumeration,
            'default-value': 'selectContents',
            validation: {
                mandatory: true
            }
        }
        
        // single variable content type identifier field for select content variable type
        composition.selectContentsContentTypeId = {
            type: 'string',
            label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_CLAUSES_VARIABLE_CONTENT_TYPE_INPUT_LABEL}}",
            description: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_CLAUSES_VARIABLE_CONTENT_TYPE_INPUT_DESCRIPTION}}",
            widget: 'edition.select-content-types',
            enumeration: null, // necessary because 'edition.select-content-types' is a widget for enumerated only
            enumerationConfig: {
                excludeReferenceTable: false
            },
            disableCondition: {condition: [{id: 'type', operator: 'neq', value: 'selectContents'}]}
        };
        
        // single variable search model identifier field for select content variable type
        composition.selectContentsSearchModelId = {
            type: 'string',
            label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_CLAUSES_VARIABLE_SEARCH_MODEL_INPUT_LABEL}}",
            description: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_CLAUSES_VARIABLE_SEARCH_MODEL_INPUT_DESCRIPTION}}",
            enumeration: response.searchUIModels,
            disableCondition: {condition: [{id: 'type', operator: 'neq', value: 'selectContents'}]}
        };
        
        // single variable solr request field for select content variable type
        composition.selectContentsSolrRequest = {
            type: 'string',
            label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_CLAUSES_VARIABLE_SOLR_REQUEST_INPUT_LABEL}}",
            description: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_CLAUSES_VARIABLE_SOLR_REQUEST_INPUT_DESCRIPTION}}",
            widget: 'edition.solr-code',
            'widget-params': {
                singleLine: true,
                height: 66,
                mode: 'text/x-solr-ametys'
            },
            disableCondition: {condition: [{id: 'type', operator: 'neq', value: 'selectContents'}]}
        };
        
        // single variable content type identifiers field for solr request variable type
        composition.solrRequestContentTypeIds = {
            type: 'string',
            label: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_CLAUSES_VARIABLE_CONTENT_TYPES_INPUT_LABEL}}",
            description: "{{i18n PLUGINS_EXTRACTION_EDIT_NODE_CLAUSES_VARIABLE_CONTENT_TYPES_INPUT_DESCRIPTION}}",
            widget: 'edition.select-content-types',
            enumeration: null, // necessary because 'edition.select-content-types' is a widget for enumerated only
            enumerationConfig: {
                excludeReferenceTable: false
            },
            disableCondition: {condition: [{id: 'type', operator: 'neq', value: 'solrRequest'}]},
            multiple: true
        };
        
        return configuration;
    },
    
    _initForm: function ()
    {
    	let me = this;
    	
    	this.callParent(arguments);
    	
    	// Initialize SolrHint to load all needed data
        SolrHint.init();
    	
    	this._form.query('container[name$="selectContentsContentTypeId"]').forEach(function(field) {
            me._updateContentType(field);
        });
    },
    
    /**
     * @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;
            
        Ext.Array.forEach(this._data.variables, function(variable, index) {
            var realIndex = index + 1; // indexes for repeater begin at 1
            values["variables["  + realIndex + "]" + this._separator + "name"] = variable.name;
            values["variables["  + realIndex + "]" + this._separator + "type"] = variable.type;
            
            if (variable.type == "solrRequest")
            {
                if (variable.contentTypeIds.length > 0)
                {
                    values["variables["  + realIndex + "]" + this._separator + "solrRequestContentTypeIds"] = variable.contentTypeIds;
                }
            }
            else
            {
                if (variable.contentTypeIds.length > 0)
                {
                    values["variables["  + realIndex + "]" + this._separator + "selectContentsContentTypeId"] = variable.contentTypeIds[0];
                }

                values["variables["  + realIndex + "]" + this._separator + "selectContentsSearchModelId"] = variable.searchModelId;
                values["variables["  + realIndex + "]" + this._separator + "selectContentsSolrRequest"] = variable.solrRequest;
            }

        }, this);
        
        repeaters.push({
            name: "variables",
            prefix: "",
            count: this._data.variables.length
        });
        
        return {
            values: values,
            repeaters: repeaters
        };
    },
    
    /**
     * @protected
     * Gets the values of the form
     * @return {Object} The form values
     */
    _getFormValues: function()
    {
        var values = this.callParent(arguments);
        // get keys without clauses variables repeaters keys
        var keys = Ext.Object.getKeys(values);
        var resultKeys = Ext.Array.filter(keys, function(key) {
            return !Ext.String.startsWith(key, "variables" + this._separator) && !Ext.String.startsWith(key, "_variables");
        }, this);
        
        // copy values except clauses repeaters keys and add clauses and clauses variables
        var result = Ext.copy({}, values, resultKeys);
        
        // get clauses variables from values
        var variables = [];
        var countVariables = values['_variables' + this._separator + 'size'];
        for (var index = 1; index <= countVariables; index++)  //the repeater begins its counter at 1
        {
            var name = values["variables[" + index + "]" + this._separator + "name"];
            var type = values["variables[" + index + "]" + this._separator + "type"];
            var searchModelId = values["variables[" + index + "]" + this._separator + "selectContentsSearchModelId"];
            var solrRequest = values["variables[" + index + "]" + this._separator + "selectContentsSolrRequest"];
            
            var contentTypeIds = [];
            if (type == "solrRequest")
            {
                contentTypeIds = values["variables[" + index + "]" + this._separator + "solrRequestContentTypeIds"];
            }
            else
            {
                var contentTypeId = values["variables[" + index + "]" + this._separator + "selectContentsContentTypeId"];
                if (contentTypeId)
                {
                    contentTypeIds = [contentTypeId];
                }
            }
            
            if (!Ext.isEmpty(name))
            {
                variables.push({
                    name: name,
                    type: type,
                    searchModelId: searchModelId,
                    solrRequest: solrRequest,
                    contentTypeIds: contentTypeIds
                });
            }
        }
        result.variables = variables;
        return result;
    },
    
    _onFieldChanged: function(field)
    {
        this.callParent(arguments);
        
        if (field.getInitialConfig("name").endsWith('selectContentsContentTypeId'))
        {
            this._updateContentType(field);
        }
    },
    
    _updateContentType: function(field)
    {
    	let solrRequestField = this._form.getRelativeField("selectContentsSolrRequest", field, false);
        solrRequestField.setContentTypes([field.getValue()]);
    }
 });