package org.treesched.examples;

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

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.treesched.DateUtils;
import org.treesched.Interval;
import org.treesched.Schedule;
import org.treesched.ant.TopScheduleElement;

/**
 * This simple Ant task displays all the times a schedule is
 * due between the given dates.
 * 
 */

public class ListSchedules extends Task {

	/** The schedule */
	private Schedule schedule;

	/** The from date as a String. */
    private String from;
    
    /** The to date as a String. */
    private String to;
    
    /**
     * Set the from date in dd-MMM-yy HH:mm format.
     * 
     * @param from The from date.
     */
    public void setFrom(String from) {
        this.from = from;
    }
    
    /**
     * Get the from date.
     * 
     * @return  The from date.
     */
    public String getFrom() {
        return from;
    }
    
    /**
     * Set the to date in dd-MMM-yy HH:mm format.
     * 
     * @param to The to date.
     */
    public void setTo(String to) {
        this.to = to;
    }
    
    /**
     * Get the to date.
     * 
     * @return The to date.
     */
    public String getTo() {
        return to;
    }
    
    /**
     * Implementation of the Task execute method.
     * 
     * @throws BuildException If the dates are invalid.
     */
	public void execute() throws BuildException {
	    if (from == null) {
	        throw new BuildException("from attribute must be specified.");
	    }
	    if (to == null) {
	        throw new BuildException("to attribute must be specified.");
	    }
	    
		SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yy HH:mm");
		Date fromDate = null;
		Date toDate = null;
		try {
		    fromDate = format.parse(from);
		    toDate = format.parse(to);
		}
		catch (ParseException e) {
		    throw new BuildException("Failed to parse date.", e);
		}
		
		do {
			Interval scheduledInterval = schedule.nextDue(fromDate);	
			System.out.println("Next due: " + scheduledInterval);
			if (scheduledInterval == null) {
			    break;
			}
			fromDate = DateUtils.oneMillisAfter(scheduledInterval.getToDate());
		}
		while (fromDate.compareTo(toDate) <= 0);

	}

	public void addSchedule(TopScheduleElement scheduleElement) {
	    this.schedule = scheduleElement;
	}
}
