package ec.gp.semantic.statistics;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

/**
 * Implementation is NOT thread safe.
 *
 * @author Tomasz Pawlak
 */
public final class Stopwatch {

    private final ThreadMXBean threadInfo;

    private long elapsed = 0L;
    private long timeStarted;
    private boolean running = false;

    public Stopwatch() {
        this.threadInfo = ManagementFactory.getThreadMXBean();
        assert this.threadInfo.isCurrentThreadCpuTimeSupported();
        assert this.threadInfo.isThreadCpuTimeEnabled();
    }

    public void start() {
        assert !this.running : "Already started";

        this.running = true;
        this.timeStarted = this.threadInfo.getCurrentThreadCpuTime();
    }

    public void stop() {
        assert this.running : "Already stopped";

        this.running = false;
        this.elapsed += this.threadInfo.getCurrentThreadCpuTime() - this.timeStarted;
    }

    /**
     * Gets elapsed time in nanoseconds (10^-9 s)
     *
     * @return
     */
    public long getTimeElapsed() {
        if (this.running) {
            return this.elapsed + this.threadInfo.getCurrentThreadCpuTime() - this.timeStarted;
        }

        return this.elapsed;
    }

    /**
     * Stops stopwatch and zeroes elapsed time;
     */
    public void reset() {
        this.running = false;
        this.elapsed = 0;
    }

    public boolean isRunning() {
        return this.running;
    }
}
