package net.sourceforge.rtf.helper.test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.Reader;

import net.sourceforge.rtf.IRTFDocumentParser;
import net.sourceforge.rtf.IRTFDocumentTransformer;
import net.sourceforge.rtf.context.fields.RTFContextField;
import net.sourceforge.rtf.context.fields.RTFContextFields;
import net.sourceforge.rtf.document.RTFDocument;
import net.sourceforge.rtf.helper.RTFTemplateBuilder;

public class TestVelocityTransformer {
    
    /**
     * @param args the args.
     */
    public static void main(String[] args) {
        try {
            /**
             * 1. Get RTFtemplate builder
             */
            RTFTemplateBuilder builder = RTFTemplateBuilder.newRTFTemplateBuilder();
            
            /**
             * 2. Get RTF parser
             */
            IRTFDocumentParser parser = builder.newRTFDocumentParser();
            
            /**
             * 3. Get RTF Document of the rtf source model
             */ 
            String rtfSourceModel = "test.rtf";
            InputStream inputStream = TestFreemarkerTransformer.class.getResourceAsStream(rtfSourceModel);
            parser.parse(inputStream);
            RTFDocument document = parser.getRTFDocument();
            
            /**
             * 4. Prepare RTF context fields
             * => set the field which must be transformed
             * In test.rtf, there is a mergefield called "date"
             */ 
            RTFContextFields context = new RTFContextFields();
            RTFContextField field = new RTFContextField();
            field.setName("$date");
            context.addMergeField(field);            
            
           /**
            * 5. Get the RTF velocity transformer
            */
            IRTFDocumentTransformer velocityTransformer = 
                builder.
                newRTFDocumentTransformer(RTFTemplateBuilder.VELOCITY_TRANSFORMER);
            RTFDocument transformedDocument = velocityTransformer.transform(document, context);
            
            /**
             * 6. Display transformed RTFDocument
             */
            Reader reader = transformedDocument.getReader();
            BufferedReader br = new BufferedReader(reader);
            int c;
            while ((c = br.read()) != -1) {
                System.out.print((char)c);
            }
            br.close();
            
        }
        catch(Exception e) {
            System.out.println("Error");
            e.printStackTrace();
        }        
    }

   
    
}
