package com.fp.frontend.filter.security;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

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

public class AuthorizationListener implements PhaseListener {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Override
    public void afterPhase(PhaseEvent event) {
        FacesContext facesContext = event.getFacesContext();
        String currentPage = facesContext.getViewRoot().getViewId();

        boolean isLoginPage = (currentPage.lastIndexOf("login.xhtml") > -1);
        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);

        NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
        //NavigationHandler nh = FacesContext.getCurrentInstance().getApplication().getNavigationHandler();

        TsafeUserDetail currentUser = session != null ? (TsafeUserDetail) session.getAttribute("TSAFEUSERDETAIL") : null;

        if (!isLoginPage && (currentUser == null)) {
            //nh.handleNavigation(facesContext, null, "login");
            try {
                facesContext.getExternalContext().dispatch("/login.xhtml");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (isLoginPage && (currentUser != null)) {
            //nh.handleNavigation(facesContext, null, "workspace");
            try {
                facesContext.getExternalContext().dispatch("/pages/workspace.xhtml");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void beforePhase(PhaseEvent event) {

    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }
}
