package gov.va.med.fw.conversion;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;

public class DateConverter implements Converter {
	// NOTE: "like" formats must be listed here in order of decreasing length (read doco for SimpleDataFormat)
	private String[] dateFormats = { "MM/dd/yyyy", "MMM dd, yyyy", "yyyyMMddHHmmssZ", "yyyyMMddHHmmss", "yyyyMMdd" };

	public DateConverter() {
		this.defaultValue = null;
		this.useDefault = false;
	}

	public DateConverter(Object defaultValue) {
		this.defaultValue = defaultValue;
		this.useDefault = true;
	}

	private Object defaultValue = null;

	private boolean useDefault = true;

	public Object convert(Class type, Object value) {
		if (value == null || (value instanceof String && ((String)value).trim().length() ==0)) {
			if (useDefault)
				return (defaultValue);

			throw new ConversionException("No value specified");
		}

		if (value instanceof Date) {
			return (value);
		}

		// loop through accepted formats
		String str = value.toString();
		Date date = null;
		for (int i = 0; i < dateFormats.length; i++) {
			date = parseDate(str, dateFormats[i]);
			if(date != null)
				return date;
		}

		if (useDefault) 
			return (defaultValue);
		
		throw new ConversionException("Unable to convert to Date: " + str);
	}

	private Date parseDate(String value, String format) {
		Date date = null;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			sdf.setLenient(false);
			date = (Date) sdf.parseObject(value);
		} catch (Exception e) { /* do nothing */
		}
		return date;
	}

    public boolean isUseDefault() {
        return useDefault;
    }

    public void setUseDefault(boolean useDefault) {
        this.useDefault = useDefault;
    }
}
