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

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

import gov.va.med.fw.io.FieldTransformer;
import gov.va.med.fw.service.AbstractComponent;
import gov.va.med.fw.util.DateUtils;
/**
 * Transformer to format a date based on the input format.
 * If Date Format is not specified, the default is
 * "yyyyMMdd"
 * 
 * @author Rajiv Patnaik
 * Created on Mar 24, 2006
 * @version 1.0
 * 
 * Copyright © 2006 VHA. All rights reserved
 */
public class DateFieldTransformer extends AbstractComponent implements FieldTransformer
{
	private static final String DEFAULT_DATE_FORMAT = "yyyyMMdd";
	
	//Fields needed to use the century format
	private static final String CENTURY_FORMAT = "CyyMMdd";
	private static final String CENTURY_1800 = "1";
	private static final String CENTURY_1900 = "2";
	private static final String CENTURY_2000 = "3";
	
	private String dateFormat;    

    /* (non-Javadoc)
     * @see gov.va.med.fw.io.FieldTransformer#transformData(java.lang.String, java.lang.Object)
     */
    public Object transformData(String fieldName, Object data) throws Exception
    {
		if(data == null)
            return null;
		
		if(!(data instanceof Date))
		{
		    throw new IllegalArgumentException("Invalid Date passed as argument " +data);
		}
		
		String formattedDate = null;
		
		if(CENTURY_FORMAT.equals(dateFormat))
		{
		    formattedDate = getCenturyFormattedDate((Date) data);
		}
		else{
		    formattedDate = new SimpleDateFormat(dateFormat).format((Date) data);
		}
		
		return formattedDate;
    }
    
    
	public void afterPropertiesSet() {
		if(dateFormat == null)
			dateFormat = DEFAULT_DATE_FORMAT;		
	}
	
    /**
     * @return Returns the dateFormat.
     */
    public String getDateFormat()
    {
        return dateFormat;
    }
    /**
     * @param dateFormat The dateFormat to set.
     */
    public void setDateFormat(String dateFormat)
    {
        this.dateFormat = dateFormat;
    }
    
    private String getCenturyFormattedDate(Date date)
    {
        Calendar cal = DateUtils.createCalendar(date);
        String century = null;
        if(cal.get(Calendar.YEAR) >= 1800 && cal.get(Calendar.YEAR) < 1900)
        {
            century = CENTURY_1800;
        }else if(cal.get(Calendar.YEAR) >= 1900 && cal.get(Calendar.YEAR) < 2000)
        {
            century = CENTURY_1900;
        }else if(cal.get(Calendar.YEAR) > 2000)
        {
            century = CENTURY_2000;
        }
        
        return century + (new SimpleDateFormat(CENTURY_FORMAT.substring(1)).format(date));
        
    }
    

}
