/*
 * Created on 4 avr. 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package org.injac.oai.util;

import java.util.Calendar;
import java.util.Date;

import org.apache.log4j.Logger;

import sun.util.calendar.CalendarDate;


/**
 * @author François Jannin
 *
 * Helpfull static functions for date checking */
public class DateChecker {
	/**
	 * Static logger
	 */
	static Logger logger = Logger.getLogger(DateChecker.class);
	/**
	 * Check date inclusion between strbegin to strend
	 * date format :  dd/mm/yyyy*/
	public static boolean checkDate(String strbegin, String strend)
    {
		boolean result=true;
		if(strbegin == null){
			strbegin = "";
		}
		if(strend == null){
			strend = "";
		}
		Date now=new Date();
    	Date begin= parseDate(strbegin);
    	Date end=parseDate(strend);
    	
    	if((begin!=null) && (end!=null))
		{
    		result = begin.before(now) && end.after(now);
    		logger.debug("begin date :"+begin.toGMTString()+"\nend date :"+end.toGMTString());
		}
		else if(begin!=null)
		{
			result = begin.before(now);
			logger.debug("begin date :"+begin.toGMTString());
		}
		else if(end!=null)
		{
			result = end.after(now);
			logger.debug("end date :"+end.toGMTString());
		}	
		return result;
    }
	/**
	 * Parse date string and return a java.util.Date object
	 * date format :  dd/mm/yyyy*/
	public static Date parseDate(String aDate)
    {
    	if(aDate.equals(""))
    		return null;
    	
    	Date result=null;
    	try
		{
        	String day=aDate.substring(0, aDate.indexOf('/'));
        	String monthyear =aDate.substring(aDate.indexOf('/')+1);
        	String month=monthyear.substring(0, aDate.indexOf('/'));
        	String year =aDate.substring(aDate.lastIndexOf('/')+1);
        	logger.debug("for "+aDate+" [day : "+day+"\tmonth : "+month+"\tyear : "+year+"]");
    		result=new Date(Integer.parseInt(year)-1900,Integer.parseInt(month)-1, Integer.parseInt(day));
		}
    	catch(Exception e)
		{
    		logger.error("bad date format(dd/mm/yyyy) :"+ aDate);
    		return null;
		}
    	return result;
    }

}
