package com.armundia.filters;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.Priority;
import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import com.armundia.v2.shared.interfaces.ISessionUser;

//@Priority(100) non funziona per i web filter
@WebFilter( filterName = "RequestLogFilter", urlPatterns = "/*")
public class RequestLogFilter implements Filter {	
	static final  Logger log = Logger.getLogger(RequestLogFilter.class.getName());

	@Inject
	private ISessionUser sessionUser;	
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		long nanoStart = System.nanoTime();
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		
		String serverId = httpRequest.getHeader("SERVER-ID");
		String requestId = httpRequest.getHeader("REQUEST-ID");
		String sessionId = httpRequest.getSession().getId();
		String user = sessionUser != null ? sessionUser.getUserId() : "NN";
		
		
//		if (toLog(httpRequest)) {		
//			log.fine(() -> "RI [S:" + serverId + " U:" + user + " J:" + sessionId + " R:" + requestId +"] " + httpRequest.getRequestURI());
//		}		
		chain.doFilter(request, response);		
		
		if (toLog(httpRequest)) {
			double msDelta = new Double(System.nanoTime() - nanoStart) / 1_000_000d;
			
			if( msDelta > 3000) {
				log.warning(() -> "REQ LONG [S:" + serverId + " U:" + user + " J:" + sessionId + " R:" + requestId +"] " + httpRequest.getRequestURI() + " TIME: " + msDelta);
			} else {
				log.info(() -> "REQ [S:" + serverId + " U:" + user + " J:" + sessionId + " R:" + requestId +"] " + httpRequest.getRequestURI() + " TIME: " + msDelta);
			}
			
		}
	}
	
	public boolean toLog(HttpServletRequest httpRequest) {
		if (httpRequest.getMethod().compareTo("OPTIONS") != 0
				 && httpRequest.getRequestURI().contains("keepAlive") == false) {
			return true;
		}
		
		return false;
	}

}
