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

import speiger.src.coreengine.utils.counters.averager.TimeAverager;

public class Timer {
	long lastTime;
	long trackerTime;
	long deltaLeft;
	TimeAverager timer = new TimeAverager();
	TimerTarget target = new TimerTarget(20);
	
	public void init() {
		lastTime = System.nanoTime();
		trackerTime = lastTime;
	}
	
	public long getDelta() {
		long time = System.nanoTime();
		deltaLeft += (time - lastTime);
		lastTime = time;
		timer.start();
		return deltaLeft;
	}
	
	public long consumeDelta() {
		long time = System.nanoTime();
		deltaLeft -= Math.max(target.getTargetNS(), time - lastTime);
		lastTime = time;
		return deltaLeft;
	}
	
	public boolean update() {
		timer.stop();
		long newTime = System.nanoTime();
		if(newTime - trackerTime >= 1000000000) {
			trackerTime = newTime;
			target.update();
			return true;
		}
		return false;
	}
	
	public TimerTarget getTarget() { return target; }
	public long getUsage() { return timer.getAverage(); }
}
