package net.sourceforge.rtf.context;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.digester.Digester;
import org.xml.sax.SAXException;

import net.sourceforge.rtf.context.fields.RTFContextBookmark;
import net.sourceforge.rtf.context.fields.RTFContextFields;
import net.sourceforge.rtf.context.fields.RTFContextField;

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

	/**
	 * Load XML configFileName file name  and return RTFContextFields.
	 * @param configFileName
	 * @return RTFContextFields
	 * @throws SAXException
	 * @throws IOException
	 */
	public static RTFContextFields getRTFContextFields(String configFileName) throws SAXException, IOException {
		return getRTFContextFields(new File(configFileName));
	}
	
	/**
	 * Load XML configFileName file and return RTFContextFields.
	 * @param configFile
	 * @return RTFContextFields
	 * @throws SAXException
	 * @throws IOException
	 */
	public static RTFContextFields getRTFContextFields(File configFile) throws SAXException, IOException {
		return getRTFContextFields(new FileInputStream(configFile));
	}
	
	
	/**
	 * Load XML configFileName file and return RTFContextFields.
	 * @param inputStream
	 * @return RTFContextFields
	 * @throws SAXException
	 * @throws IOException
	 */
	public static RTFContextFields getRTFContextFields(InputStream inputStream) throws SAXException, IOException {
		Digester digester = new Digester();
        digester.setValidating( false );
        
        digester.addObjectCreate( "fields", RTFContextFields.class );
        digester.addBeanPropertySetter( "fields/description", "description");
        // Digester Merge field
        digester.addObjectCreate( "fields/mergefield", RTFContextField.class );
        digester.addBeanPropertySetter( "fields/mergefield/list", "list");
        digester.addBeanPropertySetter( "fields/mergefield/listInfo", "listInfo");
        digester.addBeanPropertySetter( "fields/mergefield/name", "name");
        digester.addBeanPropertySetter( "fields/mergefield/description", "description");
        digester.addBeanPropertySetter( "fields/mergefield/image", "image" );
        digester.addSetNext( "fields/mergefield", "addMergeField" );
        // Digester Bookmark
        digester.addObjectCreate( "fields/bookmark", RTFContextBookmark.class );
        digester.addBeanPropertySetter( "fields/bookmark/type", "type");
        digester.addBeanPropertySetter( "fields/bookmark/name", "name");
        digester.addBeanPropertySetter( "fields/bookmark/description", "description");
        digester.addSetNext( "fields/bookmark", "addBookmark" );
        //digester.addObjectCreate( "fields/bookmark", RTFContextBookmark.class );
        return (RTFContextFields)digester.parse( inputStream );
	}

}
