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


/**
 * Provides a widget for multilingual field when comparing values
 */
Ext.define('Ametys.form.widget.MultilingualStringComparison', {
    extend: "Ametys.form.widget.TextComparison",
    
    /**
     * @private
     * Get the lang label by its code
     */
    _labelLang: function(code)
    {
        return "<span class='multilingualcode'>" + code + "</span>";
    },
    
    setValue: function(value)
    {
        this._rawValue = value;
        
        let toDisplayValues = [];
        
        var me = this;
        function _handle(compareValues, regex, base)
        {
            if (compareValues !== undefined && value)
            {
                for (let lang of Object.keys(value))
                {
                    let v1 = me._encodeValue(compareValues ? compareValues[lang] : null);
                    let v2 = me._encodeValue(value[lang]);
                    
                    let newValue = HtmlDiff.execute(base ? v1: v2, base ? v2 : v1);
                    newValue = newValue.replace(regex, "");
                    toDisplayValues.push(me._labelLang(lang) + newValue);
                }
            }
        }
        
        _handle(this._baseValue, /<del [^>]*>.*?<\/del>/g, true);
        _handle(this._futureValue, /<ins [^>]*>.*?<\/ins>/g, false);
        
        Ametys.form.widget.TextComparison.superclass.setValue.apply(this, [toDisplayValues.join('<br>')]);        
    }
});