package com.telephoners.krakyournet.ctf.logging;

import com.google.inject.Singleton;
import org.apache.commons.io.IOUtils;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.SecurityContext;
import java.io.IOException;
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());

    @Override
    public void filter(ContainerRequestContext containerRequestContext) throws IOException {
        String requestContent = IOUtils.toString(containerRequestContext.getEntityStream());
        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 = method + " " + requestURI + " from " + userName + " with content: " + requestContent;
        } else {
            logMessage = method + " " + requestURI;
        }

        LOG.log(Level.INFO, logMessage);
    }
}
