package com.telephoners.krakyournet.ctf.logging;

import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
import com.google.inject.Singleton;
import com.telephoners.krakyournet.ctf.beans.User;
import com.telephoners.krakyournet.ctf.resources.SolutionsResource;

import javax.validation.constraints.NotNull;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.SecurityContext;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.StringJoiner;
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();
        SecurityContext securityContext = containerRequestContext.getSecurityContext() ;
        String requestURI = containerRequestContext.getUriInfo().getRequestUri().toString();

        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);
    }
}
