package net.sourceforge.rtf.format;

import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;

import net.sourceforge.rtf.format.rtfcode.IRTFCode;
import net.sourceforge.rtf.util.StringUtils;

/**
 * 
 * Format RTF code like transform :
 * <ul>
 * <li> \n with \\par</li>
 * <li> \r with \\par</li>
 * <li> \t with \\tab</li>
 * </ul>
 * 
 * @version 1.0.11
 * @author <a href="mailto:angelo.zerr@gmail.com">Angelo ZERR</a>
 * 
 */
public class DefaultRTFCodeStringFormat extends Format {

    public StringBuffer formatString(String obj) {
    	return format(obj, null, null);
    }

    public StringBuffer format(Object obj, StringBuffer stringbuffer,
            FieldPosition fieldposition) {
        if (obj == null)
            return null;
        String content = null;
        if (obj instanceof IRTFCode)
            content = ((IRTFCode) obj).getContent();
        else if (obj instanceof String)
            content = (String) obj;
        if (content == null)
            return null;        
        // Replace \n\r with \\par
        String formattedContent = StringUtils.sub(content, "\n\r", "\\line ");
        // Replace \n with \\par
        formattedContent = StringUtils.sub(formattedContent, "\n", "\\line ");
        // Replace \t with \\tab
        formattedContent = StringUtils.sub(formattedContent, "\t", "\\tab ");
        // Replace àèìòù with corresponding rtf chars
        formattedContent = StringUtils.sub(formattedContent, "à", "\\'e0");
        formattedContent = StringUtils.sub(formattedContent, "è", "\\'e8");
        formattedContent = StringUtils.sub(formattedContent, "ì", "\\'ec");
        formattedContent = StringUtils.sub(formattedContent, "ò", "\\'f2");
        formattedContent = StringUtils.sub(formattedContent, "ù", "\\'f9");
        
        return new StringBuffer(formattedContent);
    }

    public Object parseObject(String s, ParsePosition parseposition) {
        // Do nothing
        return null;
    }
}
