/********************************************************************
 * Copyright © 2005 VHA. All rights reserved
 ********************************************************************/


package gov.va.med.fw.io.parser;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.lang.Validate;
import org.springframework.core.io.FileSystemResource;

import gov.va.med.fw.batchprocess.DataFileProcessExecutionContext;
import gov.va.med.fw.io.RawFileDataContainerUtils;
import gov.va.med.fw.model.lookup.Lookup;
import gov.va.med.fw.util.builder.AbstractBuilder;
import gov.va.med.fw.util.builder.BuilderException;

/**
 * Initial javadoc for class AbstractFileParserBuilder.
 * TODO - Add content here
 * 
 * Created Feb 1, 2006 3:08:18 PM
 * @author DNS   BOHMEG
 */
public abstract class AbstractFileParserBuilder extends AbstractBuilder {
	private Map converters;
	private Converter lookupConverter;
	
    private static final long serialVersionUID = -1370346746640850300L;
	public List build(Object[] args) throws BuilderException {
		return build((DataFileProcessExecutionContext) args[0], (FileSystemResource) args[1]);
	}
	
	public abstract List build(DataFileProcessExecutionContext context, FileSystemResource fileSystemResource) throws BuilderException;
	
	/**
	 * @return Returns the converters.
	 */
	public Map getConverters() {
		return converters;
	}
	/**
	 * @param converters The converters to set.
	 */
	public void setConverters(Map converters) {
		this.converters = converters;
	}	
	
	protected Converter getLookupConverter() {
		return lookupConverter;
	}
	
	public void afterPropertiesSet() throws Exception {
		super.afterPropertiesSet();		
		if(converters != null) {
			RawFileDataContainerUtils.setConverters(converters);
			
			Iterator itr = converters.entrySet().iterator();
			Map.Entry entry = null;
			Class clazz = null;
			Converter converter = null;
			while(itr.hasNext()) {
				entry = (Map.Entry) itr.next();
				clazz = Class.forName((String) entry.getKey());
				converter = (Converter) entry.getValue();
				ConvertUtils.register(converter, clazz);
				if(Lookup.class.isAssignableFrom(clazz)) {
					lookupConverter = converter;
					// due to class loading timing, this callback ensures all will be registered
					RawFileDataContainerUtils.cleanUnregisteredLookups(lookupConverter);
				}
			}
		}
		Validate.notNull(lookupConverter, "A Converter for implementations of Lookup is required");
	}
}
