package net.sourceforge.rtf.handler;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import net.sourceforge.rtf.parser.AbstractCoreRTFParser;


/**
 * RTF handler which implement AbstractCoreRTFParser to indent 
 * RTF stream on start/end group (on <b>{</b> and <b>}</b> characters)  
 * 
 * @version 1.0.0
 * @author <a href="mailto:angelo.zerr@gmail.com">Angelo ZERR</a>
 */
public class RTFIndentHandler extends AbstractCoreRTFParser {

	private static final String LINE_SEPARATOR = System
	.getProperty("line.separator");
	
	private Writer writer;
	
	public RTFIndentHandler(Writer writer) {
		this.writer = writer;
	}
	
	protected void handleKeyword(String content) throws IOException  {
		writer.write(content);
	}
	
	/**
	 * Indent start group. 
	 * @param startGroupCharacter start group character <b>{</b>.
	 * @param level of current group.
	 * @throws IOException the exception.
	 */
	protected void startGroup(char startGroupCharacter, int level) throws IOException {
		if (level > 1) 
			writer.write(LINE_SEPARATOR);
		write(String.valueOf(startGroupCharacter), level);	
	}
	
	/**
	 * Indent end group. 
	 * @param endGroupCharacter end group character <b>}</b>.
	 * @param level of current group.
	 * @throws IOException the exception.
	 */
	protected void endGroup(char endGroupCharacter, int level) throws IOException {
		writer.write(LINE_SEPARATOR);
		write(String.valueOf(endGroupCharacter), level);
	}
	

	private void write(String content, int level) throws IOException {
		for (int i = 0; i< level - 1 ; i++) {
			writer.write("    ");
		}
		writer.write(content);
	}
	
	/**
	 * Indent RTF source <b>filename</b> (arg[0])
	 * and save RTF indented content into RTF file 
	 * target indent_<b>filename</b>
	 *  
	 * @param args[0] rtf filename to indent.
	 */
	public static void main(String[] args) {
		String rtfSource = "TestIndentReader.rtf";
		if (args != null && args.length > 0) {
			rtfSource = args[0];
		}
		String rtfTarget = "indent_" + rtfSource;
		RTFIndentHandler rtfReader = null;
		try {
			FileWriter writer = new FileWriter(new File(rtfTarget));
			rtfReader = new RTFIndentHandler(writer);
			rtfReader.parse(new FileReader(rtfSource));
			writer.close();
		}catch (Exception e) {
			System.out.println("Erreur while RTFIndentHandler : " + e.getMessage());
		}
		 
	}

}
