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

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

public class FPSTimer {
	long lastTime;
	long lastDelta;
	long delta_storage;
	long time_storage;
	float particalTicks;
	TimerTarget fps = new TimerTarget(60);
	TimerTarget ups = new TimerTarget(20);
	TimeAverager mainUsage = new TimeAverager();
	
	public void init() {
		lastTime = System.nanoTime();
	}
	
	public long getDelta() {
		mainUsage.start();
		long time = System.nanoTime();
		lastDelta = time;
		return getDelta(time);
	}
	
	protected long getDelta(long time) {
		long delta = time - lastTime;
		lastTime = time;
		delta_storage += delta;
		time_storage += delta;
		float value = (delta_storage / 1000000000F);
		particalTicks = value - ((int)value);
		return delta_storage;
	}
	
	public long consumeDelta() {
		long time = System.nanoTime();
		delta_storage -= Math.max(ups.getTargetNS(), time - lastDelta);
		float value = (delta_storage / 1000000000F);
		particalTicks = value - ((int)value);
		lastDelta = time;
		return delta_storage;
	}
	
	public boolean update() {
		mainUsage.stop();
		if(time_storage >= 1000000000L) {
			fps.update();
			ups.update();
			time_storage -= 1000000000L;
			return true;
		}
		return false;
	}
	
	public TimerTarget getFPS() { return fps; }
	public TimerTarget getUPS() { return ups; }
	public long getLastTime() { return lastTime; }
	public float getParticalTime() { return particalTicks; }
	public long getUsage() { return mainUsage.getAverage(); }
}
