package biz.comm;

public class Timer {
	private final int MILLIS_IN_SECOND = 1000;
	private final int MILLIS_IN_MINUTE = 60 * 1000;
	private final int MILLIS_IN_HOUR = 60 * 60 * 1000;

	private long startTime = -1; 
	private long stopTime = -1;

	public Timer() {
	}

	public void start() {
		stopTime = -1;
		startTime = System.currentTimeMillis();
	}

	public void stop() {
		stopTime = System.currentTimeMillis();
	}

	public void reset() {
		startTime = -1;
		stopTime = -1;
	}

	public void split() {
		stopTime = System.currentTimeMillis();
	}

	public void unsplit() {
		stopTime = -1;
	}

	public void suspend() {
		stopTime = System.currentTimeMillis();
	}

	public void resume() {
		startTime += (System.currentTimeMillis() - stopTime);
		stopTime = -1;
	}

	public long getTime() {
		if (stopTime == -1) {
			if (startTime == -1) {
				return 0;
			}
			return (System.currentTimeMillis() - this.startTime);
		}
		return (this.stopTime - this.startTime);
	}

	public String toString() {
		return formatISO(getTime());
	}

	public String formatISO(long millis) {
		int hours, minutes, seconds, milliseconds;

		hours = (int) (millis / MILLIS_IN_HOUR);
		millis = millis - (hours * MILLIS_IN_HOUR);
		minutes = (int) (millis / MILLIS_IN_MINUTE);
		millis = millis - (minutes * MILLIS_IN_MINUTE);
		seconds = (int) (millis / MILLIS_IN_SECOND);
		millis = millis - (seconds * MILLIS_IN_SECOND);
		milliseconds = (int) millis;

		StringBuffer buf = new StringBuffer(32);
		buf.append(hours);
		buf.append(':');
		buf.append((char) (minutes / 10 + '0'));
		buf.append((char) (minutes % 10 + '0'));
		buf.append(':');
		buf.append((char) (seconds / 10 + '0'));
		buf.append((char) (seconds % 10 + '0'));
		buf.append('.');

		if (milliseconds < 10) {
			buf.append('0').append('0');
		} else if (milliseconds < 100) {
			buf.append('0');
		}

		buf.append(milliseconds);
		return buf.toString();
	}
} 