package cokr.xit.base;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(-10001)
public class ResponseHeaderFilter implements Filter {
    @Override
	public void destroy() {}

    @Override
	public void init(FilterConfig filterConfig) {}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {
			@Override
			public void addCookie(Cookie cookie) {
				if(cookie.getValue().isEmpty() && cookie.getMaxAge() == 0) {
					cookie.setValue("null");
				}
				cookie.setHttpOnly(true);

				super.addCookie(cookie);

			}

			@Override
			public void setContentType(String type) {
				if(type.equals("text/css")
						|| type.equals("application/javascript")
						|| type.equals("image/svg+xml")
						|| type.equals("text/html")) {
					type = type+";charset=UTF-8";
				}
				super.setContentType(type);
			}

            @Override
			public void setHeader(String name, String value) {
                if(name.equalsIgnoreCase("X-Xss-Protection")) {
                    if(super.containsHeader("Content-Type")) {
                    	if(super.getContentType() != null) {
                    		if(super.getContentType().startsWith("application/json"))
	                    		return;
                    	}
                    }
                }

                super.setHeader(name, value);
            }
        });
	}
}