package com.telephoners.krakyournet.ctf.logging;

import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
import com.google.inject.Singleton;
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.io.InputStreamReader;
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 {
        InputStream inputStream = containerRequestContext.getEntityStream();
        String requestContent = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
        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);
    }
}
