package util;

import java.util.HashMap;
import java.util.Map;

public class PTATimer {
	static Map<String, PTATimer> map = new HashMap<>();
	static PTATimer getTimer(String phase) {
		PTATimer timer = map.get(phase);
		if(timer==null)
			map.put(phase,timer=new PTATimer(phase));
		return timer;
	}
	
	public static void start() {
		start(null);
	}
	public static void report() {
		report(null);
	}
	public static void pause() {
		pause(null);
	}
	public static void stop() {
		stop(null);
	}
	
	
	public static void start(String phase) {
		getTimer(phase).istart();
	}
	public static void stop(String phase) {
		getTimer(phase).istop();
	}
	public static void pause(String phase) {
		getTimer(phase).ipause();
	}
	public static void report(String phase) {
		getTimer(phase).ireport();
	}
	
	String phase;
	long total = 0;
	long start;
	PTATimer(String phase) {
		this.phase=phase;
		this.total = 0;
	}
	void istart() {
		start = System.currentTimeMillis();
	}
	void ireport() {
		ireport(true);
	}
	void ireport(boolean continueing) {
		if(start==0)
			ireport(total,continueing);
		else 
			ireport(total+System.currentTimeMillis()-start,continueing);
	}
	private void ireport(long currentTotal, boolean continueing) {
		System.out.printf("%s" + (continueing?"(continue...)":"") + ": %.3f\n", phase, currentTotal/1000.0);
	}
	void ipause() {
		if(start==0)
			throw new RuntimeException("timer not started yet");
		total += System.currentTimeMillis()-start;
		start = 0;
	}
	void istop() {
		ireport(false);
		map.remove(phase);
	}

	static long last;
	public static boolean timeout(int i) {
		if(last==0) {
			last = System.currentTimeMillis();
			return false;
		}
		long now = System.currentTimeMillis();
		if(now-last > i*1000) {
			last = now;
			return true;
		} 
		return false;
	}
}
