package net.sourceforge.rtf.context;

/**
 * Implement AbstractRTFContextReader to Read velocity context
 * and construct XML String with all keys putted
 * into Velocity Context. This XML String can be used
 * by MS Word Macro.
 * 
 * @version 1.0.0
 * @author <a href="mailto:angelo.zerr@gmail.com">Angelo ZERR</a>
 * 
 */
public class RTFXmlFieldsReader extends AbstractRTFContextReader {
	
	private String bookmarkStartLoop;
	private String bookmarkEndLoop;
	
	private StringBuffer xmlContext;
	
	public RTFXmlFieldsReader() {
		this.bookmarkStartLoop = "START_LOOP";
		this.bookmarkEndLoop = "END_LOOP";
	}
	
	protected void startReading() {
		xmlContext = new StringBuffer(""); 
    	xmlContext.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
    	xmlContext.append("<fields>\n");
	}
	
	protected void endReading() {
		xmlContext.append("</fields>");
		
	}
	
	protected void addMergeField(String mergeFieldName, boolean mergeFieldIsList, String listInfo, boolean isImage) {
		xmlContext.append("\t<mergefield>\n");
    	xmlContext.append("\t\t<list>");
		xmlContext.append(String.valueOf(mergeFieldIsList));
		xmlContext.append("</list>\n");
		if (listInfo != null && listInfo.length() > 0) {
			xmlContext.append("\t\t<listInfo>");
			xmlContext.append(listInfo);
			xmlContext.append("</listInfo>\n");
		}
		if (isImage) {
	    	xmlContext.append("\t\t<image>");
			xmlContext.append(String.valueOf(isImage));
			xmlContext.append("</image>\n");
		}
		xmlContext.append("\t\t<name>");
		xmlContext.append(mergeFieldName);
		xmlContext.append("</name>\n");
		xmlContext.append("\t\t<description><![CDATA[...]]></description>\n");
		xmlContext.append("\t</mergefield>\n");
		
	}
	
	protected void addBookmarks() {
		// Add bokkmark START LOOP
		addBookmark(bookmarkStartLoop, bookmarkStartLoop);
		addBookmark(bookmarkEndLoop, bookmarkEndLoop);
		// Add bokkmark END LOOP
	}
	
	protected void addBookmark(String bookmarkName, String bookmarkType) {
		xmlContext.append("\t<bookmark>\n");
	    xmlContext.append("\t\t<type>");
		xmlContext.append(bookmarkType);
		xmlContext.append("</type>\n");
		xmlContext.append("\t\t<name>");
		xmlContext.append(bookmarkName);
		xmlContext.append("</name>\n");
		xmlContext.append("\t\t<description><![CDATA[...]]></description>\n");			
		xmlContext.append("\t</bookmark>\n");
	}
	
	public String getXMLFields() {
		return xmlContext.toString();
	}
}
