package com.armundia.filters;

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

import javax.annotation.Priority;
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 javax.ws.rs.HttpMethod;

//@Priority(50) Non funziona per i web filter. L'ordie si basa sul web.xml
@WebFilter(filterName = "RequestDecodeFilter" , urlPatterns = "/*")
public class RequestDecodeFilter implements Filter {
	
	static final Logger log = Logger.getLogger(RequestDecodeFilter.class.getName());

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		
		if ( httpRequest.getMethod().compareTo(HttpMethod.POST) == 0 && ( isBase64(httpRequest) || isGZip(httpRequest)) ) {
			MutableHttpServletRequest mHttpRequest = new MutableHttpServletRequest(httpRequest, isBase64(httpRequest), isGZip(httpRequest) );
			chain.doFilter(mHttpRequest, response);
		} else {
			chain.doFilter(request, response);
		}		
	}

	boolean isGZip(HttpServletRequest request) {
		String encoded = request.getHeader("ENCODED");		
		return encoded != null && encoded.compareTo("zip") == 0; 
	}
	
	boolean isBase64(HttpServletRequest request) {
		String encoded = request.getHeader("ENCODED");		
		return encoded != null && encoded.compareTo("base64") == 0;		 
	}
	
	
	boolean isJson(HttpServletRequest request) {
		return request.getContentType().contains("application/json"); 
	}
}
