/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.triz.trizservice.bean;

import java.io.IOException;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Component;

/**
 *
 * @author abdrrahim.touaibia
 */
@Component("loginBean")
@Scope("session")
public class LoginBean implements PhaseListener {

    public LoginBean(){
        
    }
    
    private Logger logger = LoggerFactory.getLogger(LoginBean.class);

    private String user;
    private String pw;
    /**
     *
     * Redirects the login request directly to spring security check. Leave this
     * method as it is to properly support spring security.
     *
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String doLogin() throws ServletException, IOException {
        System.out.println("--------------------------- doLogin -------------------------");
        logger.error("//log--------------------------- doLogin -------------------------");
        logger.info("//log--------------------------- doLogin -------------------------");
        
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();

        RequestDispatcher dispatcher = ((ServletRequest) context.getRequest())
                .getRequestDispatcher("/j_spring_security_check");

        dispatcher.forward((ServletRequest) context.getRequest(),
                (ServletResponse) context.getResponse());

        FacesContext.getCurrentInstance().responseComplete();

        return null;
    }

    public String doLogout() throws ServletException, IOException {
        System.out.println("--------------------------- doLogout -------------------------");
        logger.error("//log--------------------------- doLogout -------------------------");
        logger.info("//log--------------------------- doLogout -------------------------");
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();

        RequestDispatcher dispatcher = ((ServletRequest) context.getRequest())
                .getRequestDispatcher("/j_spring_security_logout");

        dispatcher.forward((ServletRequest) context.getRequest(),
                (ServletResponse) context.getResponse());

        FacesContext.getCurrentInstance().responseComplete();

        return null;
    }

    @Override
    public void afterPhase(PhaseEvent event) {
        System.out.println("--------------------------- afterPhase -------------------------");
        logger.error("//log--------------------------- afterPhase -------------------------");
        logger.info("//log--------------------------- afterPhase -------------------------");
    }

    /* (non-Javadoc)
     * @see javax.faces.event.PhaseListener#beforePhase(javax.faces.event.PhaseEvent)
     * 
     * Do something before rendering phase.
     */
    @Override
    public void beforePhase(PhaseEvent event) {
        System.out.println("--------------------------- beforePhase -------------------------");
        logger.error("//log--------------------------- beforePhase -------------------------");
        logger.info("//log--------------------------- beforePhase -------------------------");
        Exception e = (Exception) FacesContext.getCurrentInstance().
                getExternalContext().getSessionMap().get(WebAttributes.AUTHENTICATION_EXCEPTION);

        if (e instanceof BadCredentialsException) {
//            logger.debug("Found exception in session map: "+e);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(
                    WebAttributes.AUTHENTICATION_EXCEPTION, null);
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Username or password not valid.", "Username or password not valid"));
        }
    }

    /* (non-Javadoc)
     * @see javax.faces.event.PhaseListener#getPhaseId()
     * 
     * In which phase you want to interfere?
     */
    @Override
    public PhaseId getPhaseId() {
        System.out.println("--------------------------- getPhaseId -------------------------");
        logger.error("//log--------------------------- getPhaseId -------------------------");
        logger.info("//log--------------------------- getPhaseId -------------------------");
        return PhaseId.RENDER_RESPONSE;
    }

    public void updateMessages(boolean update) throws Exception {
        System.out.println("--------------------------- updateMessages -------------------------");
        logger.error("//log--------------------------- updateMessages -------------------------");
        logger.info("//log--------------------------- updateMessages -------------------------");
        Exception ex = (Exception) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
                .get(WebAttributes.AUTHENTICATION_EXCEPTION);

        if (ex != null) {
            logger.error("Authentication Failed! ", ex);

            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ex.getMessage()));
        }
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPw() {
        return pw;
    }

    public void setPw(String pw) {
        this.pw = pw;
    }
    
    
}