package de.jeckle.AntExtension;

import java.util.Iterator;
import java.util.Vector;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.TaskContainer;

public class Timer extends Task implements TaskContainer {
	private Vector nestedTasks = new Vector();
	private String name;
	private boolean verbose;

	public void execute() throws BuildException {
		boolean hiTi = false;

		if (verbose) {
			String vs = System.getProperty("java.version");
			System.out.println("System reports java version " + vs);

			float vf = Float.parseFloat(vs.substring(0, 3));
			if (vf < 1.5) {
				System.out.println("Using standard timer resolution");
				hiTi = false;
			} else {
				System.out.println("Using high resolution timer");
				hiTi = true;
			}
		}

		long start, end, elapsed;
		if (hiTi) {
			start = System.nanoTime();
		} else {
			start = System.currentTimeMillis();
		}
		if (verbose) {
			if (name != null) {
				System.out.println("named " + name + " started");
			} else {
				System.out.println("started");
			}
		}
		Iterator i = nestedTasks.iterator();
		while (i.hasNext()) {
			((Task) i.next()).execute();
		}
		if (hiTi) {
			end = System.nanoTime();
		} else {
			end = System.currentTimeMillis();
		}

		long hiElapsed = 0;
		if (hiTi) {
			hiElapsed = end - start;
			elapsed = hiElapsed / 1000000;
		} else {
			elapsed = end - start;
		}

		long min = elapsed / 60000;
		long minRem = elapsed % 60000;

		long sec = minRem / 1000;

		if (name != null) {
			System.out.print(
				"elapsed time for executing task named " + name + ": ");
		} else {
			System.out.print("elapsed time: ");
		}

		System.out.print(
			min
				+ " minute(s) "
				+ sec
				+ " second(s) "
				+ (elapsed - min * 60000 - sec * 1000)
				+ " millisecond(s) ");

		if (hiTi) {
			System.out.print(
				(hiElapsed - elapsed * 1000000) + " nannosecond(s)");
		}
		System.out.println();
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setVerbose(String vlevel) {
		if (vlevel.compareTo("true") == 0) {
			verbose = true;
		}
	}
	public void addTask(Task task) {
		nestedTasks.add(task);
	}
}