package com.utic.center.common.utils;

import java.util.concurrent.TimeUnit;

public class Elapsed {

	private long sTime = 0;

	public Elapsed() {
		reset();
	}

	private long getElapsed() {
		return System.nanoTime() - sTime;
	}
	public long nanoSeconds() {
		return getElapsed();
	}

	public long milliSeconds() {
		return TimeUnit.MILLISECONDS.convert(getElapsed(), TimeUnit.NANOSECONDS);
	}

	public long seconds() {
		return TimeUnit.SECONDS.convert(getElapsed(), TimeUnit.NANOSECONDS);
	}
	
	public void reset() {
		sTime = System.nanoTime();
	}

	public String elapsedTimeStr() {
		return elapsedTimeStr(getElapsed());
	}
	public String elapsedStr() {
		return elapsedStr(getElapsed());
	}
	public static String elapsedStr(long elapsed) {
		long miliSeconds = TimeUnit.MILLISECONDS.convert(elapsed, TimeUnit.NANOSECONDS);
		return String.format("Elapsed: %,d ms.", miliSeconds);
	}

	public static String elapsedTimeStr(long elapsed) {
		long hours = TimeUnit.HOURS.convert(elapsed, TimeUnit.NANOSECONDS);
		long minutes = TimeUnit.MINUTES.convert(elapsed, TimeUnit.NANOSECONDS);
		long seconds = TimeUnit.SECONDS.convert(elapsed, TimeUnit.NANOSECONDS);
		long miliSeconds = TimeUnit.MILLISECONDS.convert(elapsed, TimeUnit.NANOSECONDS) % 1000;
		long microSeconds = TimeUnit.MICROSECONDS.convert(elapsed, TimeUnit.NANOSECONDS) % 1000;
		long nanoSeconds = TimeUnit.NANOSECONDS.convert(elapsed, TimeUnit.NANOSECONDS) % 1000;

		if (hours > 0) {
			return String.format("Elapsed: %,d hr. %2d min. %2d sec. %3d ms. %3d us. %3d ns.", hours, minutes, seconds, miliSeconds, microSeconds, nanoSeconds);
		}
		if (minutes > 0) {
			return String.format("Elapsed: %2d min. %2d sec. %3d ms. %3d us. %3d ns.", minutes, seconds, miliSeconds, microSeconds, nanoSeconds);
		}
		if (seconds > 0) {
			return String.format("Elapsed: %2d sec. %3d ms. %3d us. %3d ns.", seconds, miliSeconds, microSeconds, nanoSeconds);
		}
		if (miliSeconds > 0) {
			return String.format("Elapsed: %3d ms. %3d us. %3d ns.", miliSeconds, microSeconds, nanoSeconds);
		}
		if (microSeconds > 0) {
			return String.format("Elapsed: --- ms. %3d us. %3d ns.", microSeconds, nanoSeconds);
		}
		return String.format("Elapsed: --- ms. --- us. %3d ns.", nanoSeconds);
	}

}
