package ru.yandex.webmaster3.core.http;

import ru.yandex.webmaster3.core.util.ContextTracker;

/**
 * @author aherman
 */
public class RequestTracer {
    private static final ThreadLocal<RequestTrace> traces = new ThreadLocal<>();
    private static final RequestTrace DUMMY_TRACE = new RequestTrace(0, false);

    public static RequestTrace startTrace(boolean traceQueries) {
        long wallTime = System.nanoTime();
        RequestTrace trace = new RequestTrace(wallTime, traceQueries);
        traces.set(trace);

        return trace;
    }

    public static RequestTrace getCurrentTrace() {
        RequestTrace trace = traces.get();
        if (trace == null) {
            return DUMMY_TRACE;
        } else {
            return trace;
        }
    }

    public static RequestTrace stopTrace() {
        RequestTrace trace = traces.get();
        if (trace != null) {
            trace.endRequest(System.nanoTime());
            traces.remove();
        }

        return trace;
    }

    public static ContextTracker CONTEXT_TRACKER = () -> {
        RequestTrace trace = traces.get();
        return new ContextTracker.Context() {
            @Override
            public void restoreContext() {
                traces.set(trace);
            }

            @Override
            public void clearContext() {
                traces.remove();
            }
        };
    };
}
