package com.fp.frontend.filter;

import java.io.IOException;

import javax.faces.context.FacesContext;
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.HttpSession;

import com.fp.persistence.pgeneral.safe.TsafeUserDetail;

/**
 * Servlet Filter implementation class ControlAcceso
 */
@WebFilter(filterName = "ControlAcceso", urlPatterns = {"/pages/*"})
public class ControlAcceso implements Filter {

    /**
     * Default constructor.
     */
    public ControlAcceso() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        // place your code here
        FacesContext facesContext = FacesContext.getCurrentInstance();        
        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
        TsafeUserDetail currentUser = session != null ? (TsafeUserDetail) session.getAttribute("TSAFEUSERDETAIL") : null;
        // pass the request along the filter chain
        if (currentUser != null && currentUser.getChangepassword().equalsIgnoreCase("N")) {
            //facesContext.getExternalContext().dispatch("/pages/workspace.xhtml");
            chain.doFilter(request, response);

        } else {
            facesContext.getExternalContext().dispatch("/login.xhtml");
        }

    }

    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

}
