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

/**
 * Convertor for Links
 * @private
 */
Ext.define('Ametys.plugins.cms.editor.Links.LinksConvertor', {
    /**
     * Registered to intercept getContent on richtext
     * @param {Ametys.form.field.RichText} field The richtext to convert
     * @param {tinymce.Editor} editor The current richtext editor
     * @param {Object} object The object of value to be modified
     */
    onGetContent: function(field, editor, object)
    {
        function replacer(s) 
        {
            if (!/ data-ametys-meta="[^"]*"/i.test(s))
            {
                var contentId = field.contentInfo.contentId;
                var metadataId = field.form ? field.getName().substring(field.form.getFieldNamePrefix().length) : '';
                
                return s.substring(0, s.length - 1) + ' data-ametys-meta="' + contentId + '@' + metadataId + '">';
            }
            return s;
        }

        if (object.content && field && field.contentInfo)
        {
            object.content = object.content.replace(/<a(?: [^>]*)?>/g, Ext.bind(replacer, this));
        }        
    }
});