/*
 *  Copyright 2018 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 edit a simple string or a string in multiple locales.
 */
Ext.define('Ametys.plugins.contenttypeseditor.form.field.EnhancedMultilingualString ', {
	extend : 'Ametys.form.widget.MultilingualString',
	
    alias: 'widget.enhancedmultilingualstring',
    
    _openDialog: function(languages)
    {
        this.triggerDialogBoxOpened = true;
        Ametys.plugins.contenttypeseditor.form.field.EnhancedEditMultilingualString.open({
            title: this.getFieldLabel(),
            ownerField: this,
            values: this.getValue(),
            allowBlank: this.getInitialConfig('allowBlank'),
            languages: languages,
            itemConfig: this._getItemsConfig(),
            callback: Ext.bind(this._editLanguagesCb, this)
        });
    },
    
    _updateWarning: function()
    {
        if (!this.allowBlank)
        {
            var value = this.getValue();
            if (value.isMultilingual && Ext.isObject(value.values) && !Ext.Object.isEmpty(value.values) && Ext.isEmpty(value.values[this.defaultLanguage]))
            {
                this.markWarning("{{i18n PLUGINS_CONTENTTYPESEDITOR_HELPER_EDIT_ENHANCED_MULTILINGUAL_MANDATORY_DEFAULT_LANG_EMPTY_WARN}}");  
            }
            else if (!value.isMultilingual && Ext.isEmpty(value.values))
            {
                this.markWarning("{{i18n PLUGINS_CONTENTTYPESEDITOR_HELPER_EDIT_ENHANCED_MULTILINGUAL_EDIT_SIMPLE_MANDATORY_ERROR}}");  
            }
            else
            {
                this.clearWarning();
            }
        }
    },
    
    getErrors: function (values)
    {
        var me = this,
            errors = [];
        
        if (values)
        {
            var value = values.values;  
        
	        Ext.Object.eachValue(value, function (v) {
	            errors = Ext.Array.merge(me._getErrors(v), errors);
	        });
        }
        
        if (!me.allowBlank && (!value || Ext.Object.isEmpty(value)))
        {
            errors.push(me.blankText);
        }
        
        return errors;
    },
    
    _getErrors: function (value) 
    {
        var me = this,
            errors = [],
            validator = me.validator,
            regex = me.regex,
            trimmed, isBlank;

        if (Ext.isFunction(validator)) 
        {
            var msg = validator.call(me, value);
            if (msg !== true) {
                errors.push(msg);
            }
        }
        
        trimmed = me.allowOnlyWhitespace ? value : Ext.String.trim(value);
        isBlank = trimmed.length == 0 || (value === me.emptyText && me.valueContainsPlaceholder);
        
        if (!isBlank && value.length < me.minLength) {
            errors.push(Ext.String.format(me.minLengthText, me.minLength));
        }

        if (value.length > me.maxLength) {
            errors.push(Ext.String.format(me.maxLengthText, me.maxLength));
        }
        
        if (regex && !regex.test(value)) {
            errors.push(me.regexText || me.invalidText);
        }

        return errors;
    },
    
    getValue: function ()
    {
        var value = this.callParent(arguments);
        
        if ((!value || !Ext.isObject(value)) && this.textfield.getValue())
        {
            value = {};
            value.isMultilingual = false;
            value.values = this.textfield.getValue();
        }
        
        return value;
    },
    
    _updateValueOnKeyUp: function()
    {
        var value = Ext.clone(this.value) || {};
        
        var mainValue = this.textfield.getValue();
        if (!Ext.isEmpty(mainValue))
        {
            if (value.isMultilingual)
            {
                value.values[this.defaultLanguage] = mainValue;
            }
            else
            {
                value.values = mainValue;
                value.isMultilingual = false;
            }
        }
        else if (value[this.defaultLanguage])
        {
            if (value.isMultilingual)
            {
                delete value.values[this.defaultLanguage]; // remove value for main language
            }
            else
            {
                delete value.values;
            }
        }
        
        this.setValue(value);
    },
    
    _updateDefaultValue: function(value)
    {
        if (value && Ext.isObject(value))
        {
            if (value.isMultilingual && Ext.isObject(value.values) && !Ext.Object.isEmpty(value.values) && value.values[this.defaultLanguage])
            {
                this.textfield.setValue(value.values[this.defaultLanguage]);
            }
            else if (!value.isMultilingual && !Ext.isEmpty(value.values))
            {
                this.textfield.setValue(value.values);
            }
            else
	        {
	           this.textfield.setValue(); 
	        }
        }
        else
        {
           this.textfield.setValue(); 
        }
    }
    
});