package org.kne.debug;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TimeDebugger {
	private static final ExecutorService exct=Executors.newSingleThreadExecutor();
	private Map<String,Long> timeMap=new LinkedHashMap<String,Long>();
	private Lock timeLock=new ReentrantLock();
	long tmp=-1;
	
	public void putTime(String name){
		timeLock.lock();
		try{
		long v=System.nanoTime();
		if(tmp==-1){
			timeMap.put(name,  0l);
		}else{
			timeMap.put(name,  v-tmp);
		}
		tmp=v;
		}finally {
			timeLock.unlock();
		}
	}
	
	public Map<String, Long> getTimeMap() {
		return timeMap;
	}

	public void print(){
		exct.execute(()->{
			timeLock.lock();
		
		try{
			StringBuilder sbdr=new StringBuilder();
			sbdr.append('{');
			for (Iterator<Entry<String, Long>> iterator = timeMap.entrySet().iterator(); iterator.hasNext();) {
				Entry<String, Long> type = (Entry<String, Long>) iterator.next();
				sbdr.append(type.getKey()).append('=').append(type.getValue());
				if(iterator.hasNext()) {
					sbdr.append(',');
				}
			}
			sbdr.append("}(ns)");
			System.out.println(sbdr.toString());
		}finally {
			timeLock.unlock();
		}
		});
	}
	
	public void printWithTimeFilter(long nanos){
		exct.execute(()->{
			boolean b=false;
			timeLock.lock();
		
		try{
			StringBuilder sbdr=new StringBuilder();
			sbdr.append('{');
			for (Iterator<Entry<String, Long>> iterator = timeMap.entrySet().iterator(); iterator.hasNext();) {
				Entry<String, Long> type = (Entry<String, Long>) iterator.next();
				if(type.getValue()>=nanos) {
					b=true;
				}
				sbdr.append(type.getKey()).append('=').append(type.getValue());
				if(iterator.hasNext()) {
					sbdr.append(',');
				}
			}
			sbdr.append("}(ns)");
			if(b)
			System.out.println(sbdr.toString());
		}finally {
			timeLock.unlock();
		}
		});
	}
}
