/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package phaselistener;

import db.entidades.Utilizador;
import db.providers.UtilizadoresDataProvider;
import global.Global;
import javax.faces.application.NavigationHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletRequest;
import planosactuacao.SessionBean1;
import utils.JSFHTTPUtils;
import utils.JSFUtils;
import utils.Logos;

/**
 *
 * @author lluis
 */
public class MainPhaseListener implements PhaseListener{
    private boolean firstEntry = true;
            
    public void afterPhase(PhaseEvent pe) {
       if(pe.getPhaseId() == PhaseId.RENDER_RESPONSE)
       {
            FacesContext fc = pe.getFacesContext();   
//            SessionBean1 session = JSFUtils.getSessionBean(fc);            
            String view = fc.getViewRoot().getViewId();
//            if(view.matches("/EditarPlano.jsp"))
//            {
//                session.setDisableMenu(true);                
//            }
//            else
//            {
//                session.setDisableMenu(false);                 
//            }
            System.out.println("RENDER RESPONSE VIEW : " + view);
       }
    }

    public void beforePhase(PhaseEvent pe) {
       if(pe.getPhaseId() == PhaseId.RENDER_RESPONSE)
       {
            FacesContext fc = pe.getFacesContext();           
            SessionBean1 session = JSFUtils.getSessionBean(fc);           
            String referer = JSFHTTPUtils.getReferer(pe.getFacesContext());
            System.out.println("REFERER >>" + referer + "<<");
            
            //check if comes from AnalisesAcidentes. If so, set loggedIn to true:
            if(referer != null)
            {
                if(referer.indexOf("AnaliseAcidentes") != -1)
                {
                    session.setLoggedIn(true);
                    String user = JSFUtils.getRequestParameter(fc, "user");
                    System.out.println("USER >" + user.toString() + "<");                
                }
                
            }

           
           //Determin Session Time out

            HttpServletRequest req = (HttpServletRequest) fc.getExternalContext().getRequest();            
            UIViewRoot view = fc.getViewRoot();
            
            System.out.println("SESSION VALID : " + req.isRequestedSessionIdValid());

            //if(!req.isRequestedSessionIdValid() && view.getViewId().indexOf("Login") == -1 ){
            if(!req.isRequestedSessionIdValid() && referer.indexOf("AnaliseAcidentes") == -1 ){                
                System.out.println("VIEW ID :" + view.getViewId());                
                //NavigationHandler nh = fc.getApplication().getNavigationHandler();
                //nh.handleNavigation(fc, null, "login");
                   try
                   {
                        //JSFUtils.logout(fc);
                        //JSFUtils.navigateTo(fc, "login");
                        try
                        {
                            //JSFUtils.redirect(fc, "http://localhost:8084/AnaliseAcidentesTrabalho/faces/Login.jsp");
                            JSFUtils.redirect(fc, Global.ANALISE_ACIDENTES_URL + "Login.jsp");                
                        }
                        catch(Exception ex)
                        {
                            ex.printStackTrace();
                        }

                   }
                   catch(Exception ex)
                   {
                    ex.printStackTrace();
                   }        
                
            } 
            
            //Determin if user is logged in
            //HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
            
            //SessionBean1 session = JSFUtils.getSessionBean(fc);
            boolean loggedIn = session.isLoggedIn();
            System.out.println("LOGGED IN : " + loggedIn);
            if(!loggedIn && view.getViewId().indexOf("Login") == -1 ){
                NavigationHandler nh = fc.getApplication().getNavigationHandler();
                nh.handleNavigation(fc, null, "login");
            } 
            
            //disable/enable EditarPlano menu
            String sview = fc.getViewRoot().getViewId();
            session.setRenderTopMenuImages(true);
            session.setRenderSubHeader(false);  
            
            
            //////////////
            String user_id = JSFUtils.getRequestParameter(fc, "user");
            System.out.println("PHASE LISTENER - USER ID : " + user_id);            
            Utilizador u = null;
            try
            {
                Integer userId = new Integer(Integer.parseInt(user_id));

                try
                {
                    UtilizadoresDataProvider udp = new UtilizadoresDataProvider();
                    udp.checkConnection();
                    u = udp.getUtilizador(userId);
                    session.setCurrentUser(u);
                }
                catch(Exception ex1)
                {
                    ex1.printStackTrace();
                }
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }            
            
            /////////////
            u = session.getCurrentUser();

            if(sview.matches("/EditarPlano.jsp") || sview.matches("/EnviarCorrecao.jsp") || sview.matches("/ViewPlano.jsp"))
            {
                session.setDisableMenu(false);  
                session.setDisableMenuPlanos(false);                 
                if(sview.matches("/ViewPlano.jsp"))
                {
                    if(u.getTipo().intValue() == Global.DIRECTOR_SIPRP)
                    {
                        //session.setDisableMenu(false);                          
                        session.setDisableMenuUtilizadores(false);
                    }
                    else
                    {
                        session.setDisableMenuUtilizadores(true);
                    }
                    session.setDisableMenuDadosUtilizador(false);
                    session.setRenderTopMenuImages(false);
                    session.setRenderSubHeader(true);
                }
                else if(sview.matches("/EditarPlano.jsp"))
                {
                    //session.setDisableMenuPlanos(true);
                    session.setDisableMenuPlanos(false);                    
                    session.setRenderTopMenuImages(false);
                    session.setRenderSubHeader(true);                    
                }
                
            }
            else
            {
                session.setDisableMenu(false);  
                if(sview.matches("/ListaPlanos.jsp"))
                {
                    session.setDisableMenuPlanos(true);                    
                }
            }
            
            //insert logos
            
            Integer empresaId = u.getEmpresa_id();
            System.out.println("LOGO EMPRESA ID B : " + empresaId.toString());            
            Logos logos = new Logos();
            String logourl = logos.getLogo(fc, empresaId);
            session.setLogoEmpresaUrl(logourl);
            System.out.println("LOGO URL : " + logourl);                
            System.out.println("VIEW : " + view);            
        }
    }

    public PhaseId getPhaseId() {
        return PhaseId.ANY_PHASE;
    }

}
