package com.telephoners.krakyournet.ctf.logging;

import com.google.inject.Singleton;
import org.apache.commons.io.IOUtils;
import org.glassfish.jersey.server.ContainerRequest;
import org.glassfish.jersey.server.ContainerResponse;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.SecurityContext;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by adam on 20.03.16.
 */

@Singleton
public class LoggingFilter implements ContainerRequestFilter {
    private static final Logger LOG = Logger.getLogger(LoggingFilter.class.getName());
    private final String LOG_MESSAGE = "%s request for %s";
    private final String LOG_MESSAGE_WITH_USERNAME = "%s request for %s from %s with content: %s";

    @Override
    public void filter(ContainerRequestContext containerRequestContext) throws IOException {
        InputStream inputStream = containerRequestContext.getEntityStream();
        String requestContent = IOUtils.toString(inputStream);
        String method = containerRequestContext.getMethod();
        String requestURI = containerRequestContext.getUriInfo().getRequestUri().toString();
        SecurityContext securityContext = containerRequestContext.getSecurityContext() ;

        String logMessage;

        if (securityContext.getUserPrincipal() != null) {
            String userName = securityContext.getUserPrincipal().getName();
            logMessage = String.format(LOG_MESSAGE_WITH_USERNAME, method, requestURI, userName, requestContent);
        } else {
            logMessage = String.format(LOG_MESSAGE, method, requestURI);
        }

        LOG.log(Level.INFO, logMessage);

        // ensuring the data is still available for the rest of the application
        inputStream = IOUtils.toInputStream(requestContent, "UTF-8");
        containerRequestContext.setEntityStream(inputStream);
    }

}
