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

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

public class CountdownSync {
	boolean initialised = false;
	RunningAvg sleepDurations = new RunningAvg(10);
	RunningAvg yieldDurations = new RunningAvg(10);
	
	public void sync(long expectedNanoTime) {
		if(!initialised) {
			initialised = true;
			sleepDurations.init(1000000);
			yieldDurations.init((int)(-(System.nanoTime() - System.nanoTime()) * 1.333));
		}
		long nextFrame = System.nanoTime() + expectedNanoTime;
		try {
			for(long t0 = System.nanoTime(),t1;(nextFrame - t0) > sleepDurations.avg();t0 = t1) {
				Thread.sleep(1);
				sleepDurations.add((t1 = System.nanoTime()) - t0);
			}
			sleepDurations.dampenForLowResTicker();
			
			for(long t0 = System.nanoTime(),t1;(nextFrame - t0) > yieldDurations.avg();t0 = t1) {
				Thread.yield();
				yieldDurations.add((t1 = System.nanoTime()) - t0);
			}
		}
		catch(InterruptedException e) {}
	}
}
