package org.treesched.schedules;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.treesched.RegularSchedule;

/**
 * This schedule returns an interval 
 * from the given time to the interval time later.
 * Commonly used within a time schedule.
 * <p>
 * Typical configuration is:
 * <code><pre>
 * &lt;interval interval="00:20"/>&gt;
 * </pre></code>
 *
 * @author Rob Gordon
 */

final public class IntervalSchedule extends RegularSchedule implements Serializable {

    private static final long serialVersionUID = 20050226;
    
	public static final String DEFAULT_DATE_FORMAT = "HH:mm";
	private String format = DEFAULT_DATE_FORMAT;

	/**
	 * Milliseconds at midnight, the previous night.
	 */
	private final long zeroHour;
	
	
	/**
	 * Milliseconds for the interval.
	 */
	private Long intervalMillis;

	/**
	 * Constructor.
	 */
	public IntervalSchedule() {
		// why isn't 00:00 0? don't know but define our own zero
		SimpleDateFormat format = new SimpleDateFormat("HH:mm");
		long maybe = 0; 
		try {
			maybe = format.parse("00:00").getTime();
		}
		catch (ParseException e) {
			// This should never happen.
		}
	    zeroHour = maybe;
	}		

	/**
	 * Set the date format to use for translating string attributes.
	 * 
	 * @param dateFormat The date format.
	 */		
	public void setFormat(String dateFormat) {	
		this.format = dateFormat;
	}

	/**
	 * Get the date format used for translating string attributes.
	 * 
	 * @return The date format being used.
	 */
	public String getFormat() {		
		return this.format;	
	}
	
	/**
	 * Set the interval.
	 * 
	 * @param interval The interval.
	 * @throws ParseException If the interval is not a valid date.
	 */
	public void setInterval(String interval) throws ParseException {		
		SimpleDateFormat sdf = new SimpleDateFormat(format);		
		intervalMillis = new Long(sdf.parse(interval).getTime() - zeroHour);
	}

	/*
	 *  (non-Javadoc)
	 * @see org.treesched.RegularSchedule#next(java.util.Date)
	 */
    public Date next(Date from) {
        if (intervalMillis == null) {
            return new Date(Long.MAX_VALUE);
        }
        return new Date(from.getTime() + intervalMillis.longValue());
    }
}
