package org.treesched.examples;

import java.util.Date;

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

/**
 * This is a simple Ant task that waits until it is next
 * due to advance. It's shows how treesched could be used
 * to hold a build until a certain time.
 */

public class AntWait extends Task {

	/** The schedule */
	private Schedule schedule;
	
	/**
	 * Implement the Task execute method.
	 */
	public void execute() throws BuildException {
		
		Interval nextDue = schedule.nextDue(new Date());
		log("Next due: " + nextDue);

		// when the schedule ends, return.
		if (nextDue == null) {
			return;
		}

		long sleep = 0;
		// The thread might be woken before it's due so loop until it is due.
		do {	
			Date now = new Date();
			sleep = nextDue.getFromDate().getTime() - now.getTime();
			if (sleep > 0) {	
				log("sleeping: " + sleep + "ms");
				try {
					synchronized (this) {
						wait(sleep);
					}
				}
				catch (InterruptedException e) {
					// ignore.
				}
			}
		} while (sleep > 0);
		log("Time to continue.");
	}
	
	/**
	 * Add a schedule element.
	 * 
	 * @param scheduleElement The schedule.
	 */
	public void addSchedule(TopScheduleElement scheduleElement) {
	    this.schedule = scheduleElement;
	}
}
