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


package gov.va.med.esr.common.infra;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;

import gov.va.med.fw.service.AbstractComponent;
import gov.va.med.fw.util.builder.Builder;
import gov.va.med.fw.util.builder.BuilderException;

/**
 * Initial javadoc for class ImpreciseDateConverter.
 * TODO - Add content here
 * 
 * Created Mar 14, 2006 11:25:48 PM
 * @author DNS   BOHMEG
 */
public class ImpreciseDateConverter extends AbstractComponent implements
		Converter {
	private Builder impreciseDateBuilder;

	/* (non-Javadoc)
	 * @see org.apache.commons.beanutils.Converter#convert(java.lang.Class, java.lang.Object)
	 */
	public Object convert(Class arg0, Object arg1) {
		if (arg1 instanceof ImpreciseDate)
			return arg1;
		
		if(! (arg1 instanceof String) )		
			throw new ConversionException("Can not convert class type [" + arg1.getClass().getName() + "] to ImpreciseDate");
		
		if (StringUtils.isBlank((String) arg1))
			return null;
		
		ImpreciseDate date = null;
		try {
			// try most comprehensive format first
			date = (ImpreciseDate) impreciseDateBuilder.build(arg1);
		} catch(BuilderException e) {
			// try other loosely allowed formats
			date = new ImpreciseDate((String) arg1);
		}
		return date;
	}

	public void afterPropertiesSet() {
		Validate.notNull(impreciseDateBuilder);
	}
	
	/**
	 * @return Returns the impreciseDateBuilder.
	 */
	public Builder getImpreciseDateBuilder() {
		return impreciseDateBuilder;
	}

	/**
	 * @param impreciseDateBuilder The impreciseDateBuilder to set.
	 */
	public void setImpreciseDateBuilder(Builder impreciseDateBuilder) {
		this.impreciseDateBuilder = impreciseDateBuilder;
	}
}
