package net.sourceforge.rtf.document.transformer.fields;

import net.sourceforge.rtf.document.RTFField;

/**
 * 
 * @version 1.0.0
 * @author <a href="mailto:angelo.zerr@gmail.com">Angelo ZERR</a>
 * 
 */
public class DefaultRTFMergeFieldTransform implements IRTFFieldTransform {

    public void transform(RTFField field, boolean fieldIsList,
            IRTFFieldNameTransform fieldNameTransform) {
        /*
         * MERGEFIELD code RTF example : {\field\flddirty {\*\fldinst
         * {\b\cf17\lang1036\langfe2057\langnp1036\insrsid331776\charrsid5667574
         * MERGEFIELD $personne.Name \\* MERGEFORMAT } } {\fldrslt
         * {\b\cf17\lang1024\langfe1024\noproof\langnp1036\insrsid331776\charrsid5667574
         * \'ab$personne.Name\'bb } } }
         * 
         * We must get string which begins by {\fldrslt
         */
        String fieldName = fieldNameTransform.getTransformedFieldName(
                fieldIsList, field.getName());
        String fieldContent = field.getRTFContentOfSimpleElement();
        fieldContent = fieldContent.trim();
        int indexStart = fieldContent.indexOf("{\\fldrslt");
        if (indexStart != -1) {
            indexStart = indexStart + 9;
            String newFieldContent = fieldContent.substring(indexStart,
                    fieldContent.length() - 2);
            /*
             * newFieldContent = newFieldContent.replaceAll("\\\\'ab", "");
             * newFieldContent = newFieldContent.replaceAll("\\\\'bb", "");
             */
            int indexQuoteAB = newFieldContent.indexOf("\\'ab");
            int indexQuoteBB = newFieldContent.indexOf("\\'bb");
            if (indexQuoteAB != -1 && indexQuoteBB != -1) {
                newFieldContent = newFieldContent.substring(0, indexQuoteAB)
                        + fieldName
                        + newFieldContent.substring(indexQuoteBB + 4,
                                newFieldContent.length());
            }
            else {
                // Word 95 => it's not \'ab but \ldblquote and not \'bb => rdblquote
                 // {\b\f2\cf2\lang1024 \ldblquote $employeeName\rdblquote }
                int indexLdblquote = newFieldContent.indexOf("\\ldblquote");
                int indexRdblquote = newFieldContent.indexOf("\\rdblquote");
                if (indexLdblquote != -1 && indexRdblquote != -1) {
                    newFieldContent = newFieldContent.substring(0, indexLdblquote)
                    + fieldName
                    + newFieldContent.substring(indexRdblquote + 10,
                            newFieldContent.length());
                }
                
            }
            newFieldContent = newFieldContent.trim();
            field.replaceElement(newFieldContent);
        } else
            field.replaceElement(fieldName);
    }

}
