package speiger.src.coreengine.utils.counters.timers;

import java.util.concurrent.TimeUnit;

public class Stopwatch {
	long start;
	long elapsedTime;
	boolean running;
	
	public Stopwatch start() {
		if(running) throw new IllegalStateException("Stopwatch is started");
		start = System.nanoTime();
		running = true;
		return this;
	}
	
	public Stopwatch stop() {
		if(!running) throw new IllegalStateException("Stopwatch is stopped");
		running = false;
		elapsedTime += System.nanoTime() - start;
		return this;
	}
	
	public Stopwatch reset() {
		running = false;
		elapsedTime = 0L;
		return this;
	}
	
	public long getTime() { return running ? (System.nanoTime() - start) + elapsedTime : elapsedTime; }
	public long getTime(TimeUnit unit) { return unit.convert(getTime(), TimeUnit.NANOSECONDS); }
	public boolean hasTimeLeft(TimeUnit unit, long time) { return getTime(unit) < time; }
	public boolean hasTimeLeft(long time) { return getTime() < time; }
}
