package com.rjconsultores.ventaboletos.filters;

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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.rjconsultores.ventaboletos.constantes.ConstantesFuncionSistema;
import com.rjconsultores.ventaboletos.utilerias.UsuarioLogado;

@WebFilter(filterName = "authenticationPricingRS", urlPatterns = "/rest/pricing/*")
public class AuthenticationPricingRS implements Filter {
	
	private static Logger log = LogManager.getLogger(AuthenticationPricingRS.class);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		try {
			if (request instanceof HttpServletRequest) {
				HttpServletRequest req = ((HttpServletRequest) request);
				HttpServletResponse res = null;
				
				if (response instanceof HttpServletResponse) {
					res = ((HttpServletResponse) response);
				}
				
				if (req != null && res != null) {
					String auth = req.getHeader("Authorization");
					if (StringUtils.isNotBlank(auth) && UsuarioLogado.getUsuarioLogado() != null && UsuarioLogado.getUsuarioLogado().isPermisoClave(ConstantesFuncionSistema.CLAVE_ADM_PRICING_MODIFICACAOMASSIVAWS)) {
						chain.doFilter(request, response);
					} else {
						res.setHeader("WWW-Authenticate", "BASIC realm=\"AlteraPricingRS\"");
						res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
						return;
					}
				}
			}
		} catch (Exception e) {
			log.error(e.toString(), e);

			HttpServletResponse httpServletResponse = (HttpServletResponse) response;
			httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			
			((HttpServletResponse) response).sendError(HttpServletResponse.SC_BAD_REQUEST);
		}
	}

	@Override
	public void destroy() {
	}
	
}
