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

import net.sourceforge.rtf.document.RTFField;
import net.sourceforge.rtf.util.StringUtils;

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

	public void transform(RTFField field, boolean fieldIsList, IRTFFieldNameTransform fieldNameTransform) {
		String fieldName = field.getName();
		/* HYPERLINK field code RTF example : 
	    /* {\field
	        {\*\fldinst 
	            {\insrsid9655237  HYPERLINK "mailto:$developers.Email" 

	            }
	            {\insrsid9655237 
	                {\*\datafield 00d0c9ea79f9bace118c8200aa004ba90b0200000003000000e0c9ea79f9bace118c8200aa004ba90b320000006d00610069006c0074006f003a00240064006500760065006c006f0070006500720073002e0045006d00610069006c000000
	                }
	            }
	        }
	        {\fldrslt 
	            {\cs16\ ul\cf2\insrsid9655237\charrsid9655237 mailto:$developers.Email
	            }
	        }
	    }*/
		 // the section datafield contains link in binary, this section must be remove
		if (fieldName != null) {
			String fieldContent = field.getRTFContentOfSimpleElement();
			//fieldContent = fieldContent.replaceAll("\"}", " \"}");
			//fieldContent = fieldContent.replaceAll("mailto:", "mailto: ");
			int indexStartDatafield = fieldContent.indexOf("{\\*\\datafield ");
			if (indexStartDatafield != -1) {
				int indexEndDataField = fieldContent.indexOf("}", indexStartDatafield);
				String startFieldContent = fieldContent.substring(0, indexStartDatafield);
				String endFieldContent = fieldContent.substring(indexEndDataField + 1, fieldContent.length());
				fieldContent = startFieldContent + endFieldContent;
			}
            // Replace name
            String newFieldName = fieldNameTransform.getTransformedFieldName(fieldIsList, fieldName);
            if (!fieldName.equals(newFieldName)) {
                fieldContent = StringUtils.sub(fieldContent, fieldName, newFieldName);                
            }
            
			field.replaceElement(fieldContent);
		}
	}


}
