package com.mazebert.presenters.jaxrs.filter;

import com.mazebert.BusinessLogic;
import com.mazebert.usecases.admin.AddTrackingData;
import org.glassfish.jersey.server.ContainerRequest;

import javax.annotation.Priority;
import javax.ws.rs.container.*;
import javax.ws.rs.ext.Provider;

@Provider
@PreMatching
@Priority(1)
public class RequestMonitoring implements ContainerRequestFilter, ContainerResponseFilter {

    public static final String MONITORING_START_TIME = "com.re.monitoring.start";

    @Override
    public void filter(ContainerRequestContext requestContext) {
        requestContext.setProperty(MONITORING_START_TIME, System.nanoTime());
    }


    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
        ContainerRequest containerRequest = (ContainerRequest) requestContext;

        if (didMatch(containerRequest)) {
            AddTrackingData.Request request = new AddTrackingData.Request();
            request.event = "r:" + containerRequest.getPath(false);
            request.startNanos = (Long) requestContext.getProperty(MONITORING_START_TIME);
            request.endNanos = System.nanoTime();
            request.nowMillis = System.currentTimeMillis();

            BusinessLogic.getInstance().execute(request);
        }
    }

    private boolean didMatch(ContainerRequest request) {
        return !request.getUriInfo().getMatchedResources().isEmpty();
    }
}
