/*
 * FichaUtilizador.java
 *
 * Created on October 11, 2007, 9:49 AM
 * Copyright lluis
 */
package analiseacidentestrabalho;

import com.sun.rave.web.ui.appbase.AbstractPageBean;
import com.sun.rave.web.ui.component.Body;
import com.sun.rave.web.ui.component.Button;
import com.sun.rave.web.ui.component.Checkbox;
import com.sun.rave.web.ui.component.DropDown;
import com.sun.rave.web.ui.component.Form;
import com.sun.rave.web.ui.component.Head;
import com.sun.rave.web.ui.component.HiddenField;
import com.sun.rave.web.ui.component.Html;
import com.sun.rave.web.ui.component.Hyperlink;
import com.sun.rave.web.ui.component.ImageComponent;
import com.sun.rave.web.ui.component.Link;
import com.sun.rave.web.ui.component.Page;
import com.sun.rave.web.ui.component.PanelGroup;
import com.sun.rave.web.ui.component.PasswordField;
import com.sun.rave.web.ui.component.StaticText;
import com.sun.rave.web.ui.component.TextField;
import com.sun.rave.web.ui.model.SingleSelectOptionsList;
import db.AnalisesDataProvider;
import db.UtilizadoresDataProvider;
import javax.faces.FacesException;
import javax.faces.component.html.HtmlPanelGrid;
import javax.faces.event.ValueChangeEvent;
import javax.servlet.http.HttpServletRequest;
import utils.Utils;
import global.Global;
import javax.servlet.ServletContext;

/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 */
public class FichaUtilizador extends AbstractPageBean {
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">
    private int __placeholder;
    
    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    
    private Page page1 = new Page();
    
    public Page getPage1() {
        return page1;
    }
    
    public void setPage1(Page p) {
        this.page1 = p;
    }
    
    private Html html1 = new Html();
    
    public Html getHtml1() {
        return html1;
    }
    
    public void setHtml1(Html h) {
        this.html1 = h;
    }
    
    private Head head1 = new Head();
    
    public Head getHead1() {
        return head1;
    }
    
    public void setHead1(Head h) {
        this.head1 = h;
    }
    
    private Link link1 = new Link();
    
    public Link getLink1() {
        return link1;
    }
    
    public void setLink1(Link l) {
        this.link1 = l;
    }
    
    private Body body1 = new Body();
    
    public Body getBody1() {
        return body1;
    }
    
    public void setBody1(Body b) {
        this.body1 = b;
    }
    
    private Form form1 = new Form();
    
    public Form getForm1() {
        return form1;
    }
    
    public void setForm1(Form f) {
        this.form1 = f;
    }

    private HtmlPanelGrid gridBase1 = new HtmlPanelGrid();

    public HtmlPanelGrid getGridBase1() {
        return gridBase1;
    }

    public void setGridBase1(HtmlPanelGrid hpg) {
        this.gridBase1 = hpg;
    }

    private HtmlPanelGrid gridLayout1 = new HtmlPanelGrid();

    public HtmlPanelGrid getGridLayout1() {
        return gridLayout1;
    }

    public void setGridLayout1(HtmlPanelGrid hpg) {
        this.gridLayout1 = hpg;
    }

    private HtmlPanelGrid gridPanel1 = new HtmlPanelGrid();

    public HtmlPanelGrid getGridPanel1() {
        return gridPanel1;
    }

    public void setGridPanel1(HtmlPanelGrid hpg) {
        this.gridPanel1 = hpg;
    }

    private PanelGroup groupPanel1 = new PanelGroup();

    public PanelGroup getGroupPanel1() {
        return groupPanel1;
    }

    public void setGroupPanel1(PanelGroup pg) {
        this.groupPanel1 = pg;
    }

    private ImageComponent image1 = new ImageComponent();

    public ImageComponent getImage1() {
        return image1;
    }

    public void setImage1(ImageComponent ic) {
        this.image1 = ic;
    }

    private ImageComponent image2 = new ImageComponent();

    public ImageComponent getImage2() {
        return image2;
    }

    public void setImage2(ImageComponent ic) {
        this.image2 = ic;
    }

    private PanelGroup groupPanel2 = new PanelGroup();

    public PanelGroup getGroupPanel2() {
        return groupPanel2;
    }

    public void setGroupPanel2(PanelGroup pg) {
        this.groupPanel2 = pg;
    }

    private StaticText lblUser = new StaticText();

    public StaticText getLblUser() {
        return lblUser;
    }

    public void setLblUser(StaticText st) {
        this.lblUser = st;
    }

    private StaticText staticText1 = new StaticText();

    public StaticText getStaticText1() {
        return staticText1;
    }

    public void setStaticText1(StaticText st) {
        this.staticText1 = st;
    }

    private Hyperlink lnkEditUser = new Hyperlink();

    public Hyperlink getLnkEditUser() {
        return lnkEditUser;
    }

    public void setLnkEditUser(Hyperlink h) {
        this.lnkEditUser = h;
    }

    private StaticText staticText2 = new StaticText();

    public StaticText getStaticText2() {
        return staticText2;
    }

    public void setStaticText2(StaticText st) {
        this.staticText2 = st;
    }

    private Hyperlink lnkLogout = new Hyperlink();

    public Hyperlink getLnkLogout() {
        return lnkLogout;
    }

    public void setLnkLogout(Hyperlink h) {
        this.lnkLogout = h;
    }

    private HtmlPanelGrid gridMsg1 = new HtmlPanelGrid();

    public HtmlPanelGrid getGridMsg1() {
        return gridMsg1;
    }

    public void setGridMsg1(HtmlPanelGrid hpg) {
        this.gridMsg1 = hpg;
    }

    private StaticText txtMsg = new StaticText();

    public StaticText getTxtMsg() {
        return txtMsg;
    }

    public void setTxtMsg(StaticText st) {
        this.txtMsg = st;
    }

    private HtmlPanelGrid gridPanel2 = new HtmlPanelGrid();

    public HtmlPanelGrid getGridPanel2() {
        return gridPanel2;
    }

    public void setGridPanel2(HtmlPanelGrid hpg) {
        this.gridPanel2 = hpg;
    }

    private HtmlPanelGrid gridPanel3 = new HtmlPanelGrid();

    public HtmlPanelGrid getGridPanel3() {
        return gridPanel3;
    }

    public void setGridPanel3(HtmlPanelGrid hpg) {
        this.gridPanel3 = hpg;
    }

    private PanelGroup groupPanel3 = new PanelGroup();

    public PanelGroup getGroupPanel3() {
        return groupPanel3;
    }

    public void setGroupPanel3(PanelGroup pg) {
        this.groupPanel3 = pg;
    }

    private StaticText stCriarEditar = new StaticText();

    public StaticText getStCriarEditar() {
        return stCriarEditar;
    }

    public void setStCriarEditar(StaticText st) {
        this.stCriarEditar = st;
    }

    private StaticText staticText4 = new StaticText();

    public StaticText getStaticText4() {
        return staticText4;
    }

    public void setStaticText4(StaticText st) {
        this.staticText4 = st;
    }

    private HtmlPanelGrid gridPanel4 = new HtmlPanelGrid();

    public HtmlPanelGrid getGridPanel4() {
        return gridPanel4;
    }

    public void setGridPanel4(HtmlPanelGrid hpg) {
        this.gridPanel4 = hpg;
    }

    private StaticText staticText5 = new StaticText();

    public StaticText getStaticText5() {
        return staticText5;
    }

    public void setStaticText5(StaticText st) {
        this.staticText5 = st;
    }

    private DropDown drpTipo = new DropDown();

    public DropDown getDrpTipo() {
        return drpTipo;
    }

    public void setDrpTipo(DropDown dd) {
        this.drpTipo = dd;
    }

    private StaticText staticText6 = new StaticText();

    public StaticText getStaticText6() {
        return staticText6;
    }

    public void setStaticText6(StaticText st) {
        this.staticText6 = st;
    }

    private HtmlPanelGrid gridPanel5 = new HtmlPanelGrid();

    public HtmlPanelGrid getGridPanel5() {
        return gridPanel5;
    }

    public void setGridPanel5(HtmlPanelGrid hpg) {
        this.gridPanel5 = hpg;
    }

    private DropDown drpNome = new DropDown();

    public DropDown getDrpNome() {
        return drpNome;
    }

    public void setDrpNome(DropDown dd) {
        this.drpNome = dd;
    }

    private TextField txtNome = new TextField();

    public TextField getTxtNome() {
        return txtNome;
    }

    public void setTxtNome(TextField tf) {
        this.txtNome = tf;
    }

    private StaticText staticText7 = new StaticText();

    public StaticText getStaticText7() {
        return staticText7;
    }

    public void setStaticText7(StaticText st) {
        this.staticText7 = st;
    }

    private TextField txtLogin = new TextField();

    public TextField getTxtLogin() {
        return txtLogin;
    }

    public void setTxtLogin(TextField tf) {
        this.txtLogin = tf;
    }

    private StaticText staticText8 = new StaticText();

    public StaticText getStaticText8() {
        return staticText8;
    }

    public void setStaticText8(StaticText st) {
        this.staticText8 = st;
    }

    private PasswordField txtPassword = new PasswordField();

    public PasswordField getTxtPassword() {
        return txtPassword;
    }

    public void setTxtPassword(PasswordField pf) {
        this.txtPassword = pf;
    }

    private StaticText staticText9 = new StaticText();

    public StaticText getStaticText9() {
        return staticText9;
    }

    public void setStaticText9(StaticText st) {
        this.staticText9 = st;
    }

    private TextField txtEmail = new TextField();

    public TextField getTxtEmail() {
        return txtEmail;
    }

    public void setTxtEmail(TextField tf) {
        this.txtEmail = tf;
    }

    private StaticText lblCap = new StaticText();

    public StaticText getLblCap() {
        return lblCap;
    }

    public void setLblCap(StaticText st) {
        this.lblCap = st;
    }

    private TextField txtCap = new TextField();

    public TextField getTxtCap() {
        return txtCap;
    }

    public void setTxtCap(TextField tf) {
        this.txtCap = tf;
    }

    private StaticText lblCedula = new StaticText();

    public StaticText getLblCedula() {
        return lblCedula;
    }

    public void setLblCedula(StaticText st) {
        this.lblCedula = st;
    }

    private StaticText stCedula = new StaticText();

    public StaticText getStCedula() {
        return stCedula;
    }

    public void setStCedula(StaticText st) {
        this.stCedula = st;
    }

    private HtmlPanelGrid gridPanel6 = new HtmlPanelGrid();

    public HtmlPanelGrid getGridPanel6() {
        return gridPanel6;
    }

    public void setGridPanel6(HtmlPanelGrid hpg) {
        this.gridPanel6 = hpg;
    }

    private PanelGroup groupPanel4 = new PanelGroup();

    public PanelGroup getGroupPanel4() {
        return groupPanel4;
    }

    public void setGroupPanel4(PanelGroup pg) {
        this.groupPanel4 = pg;
    }

    private StaticText staticText13 = new StaticText();

    public StaticText getStaticText13() {
        return staticText13;
    }

    public void setStaticText13(StaticText st) {
        this.staticText13 = st;
    }

    private HtmlPanelGrid gridPanel7 = new HtmlPanelGrid();

    public HtmlPanelGrid getGridPanel7() {
        return gridPanel7;
    }

    public void setGridPanel7(HtmlPanelGrid hpg) {
        this.gridPanel7 = hpg;
    }

    private Button butCancelar = new Button();

    public Button getButCancelar() {
        return butCancelar;
    }

    public void setButCancelar(Button b) {
        this.butCancelar = b;
    }

    private PanelGroup groupPanel5 = new PanelGroup();

    public PanelGroup getGroupPanel5() {
        return groupPanel5;
    }

    public void setGroupPanel5(PanelGroup pg) {
        this.groupPanel5 = pg;
    }

    private Button butApagar = new Button();

    public Button getButApagar() {
        return butApagar;
    }

    public void setButApagar(Button b) {
        this.butApagar = b;
    }

    private Button butGravar = new Button();

    public Button getButGravar() {
        return butGravar;
    }

    public void setButGravar(Button b) {
        this.butGravar = b;
    }

    private HiddenField hidConfDelUser = new HiddenField();

    public HiddenField getHidConfDelUser() {
        return hidConfDelUser;
    }

    public void setHidConfDelUser(HiddenField hf) {
        this.hidConfDelUser = hf;
    }
    
    // </editor-fold>
    private boolean isPostData = false;
    
    private final static int SEG = 1;
    private final static int RH = 2;    
    private final static int HS = 3;        
    private final static int MEDICO = 5;        
    private final static int GESTOR = 6;        
    private final static int DIRECTOR_RH = 7;            
    private final static int DIRECTOR_SIPRP = 8;                

    private StaticText staticText12 = new StaticText();

    public StaticText getStaticText12() {
        return staticText12;
    }

    public void setStaticText12(StaticText st) {
        this.staticText12 = st;
    }

    private DropDown drpEstabelecimentos = new DropDown();

    public DropDown getDrpEstabelecimentos() {
        return drpEstabelecimentos;
    }

    public void setDrpEstabelecimentos(DropDown dd) {
        this.drpEstabelecimentos = dd;
    }

    private SingleSelectOptionsList drpEstabelecimentosDefaultOptions = new SingleSelectOptionsList();

    public SingleSelectOptionsList getDrpEstabelecimentosDefaultOptions() {
        return drpEstabelecimentosDefaultOptions;
    }

    public void setDrpEstabelecimentosDefaultOptions(SingleSelectOptionsList ssol) {
        this.drpEstabelecimentosDefaultOptions = ssol;
    }

    private StaticText lblResponsavelLoja = new StaticText();

    public StaticText getLblResponsavelLoja() {
        return lblResponsavelLoja;
    }

    public void setLblResponsavelLoja(StaticText st) {
        this.lblResponsavelLoja = st;
    }

    private Checkbox chkResponsavelLoja = new Checkbox();

    public Checkbox getChkResponsavelLoja() {
        return chkResponsavelLoja;
    }

    public void setChkResponsavelLoja(Checkbox c) {
        this.chkResponsavelLoja = c;
    }

    private StaticText staticText3 = new StaticText();

    public StaticText getStaticText3() {
        return staticText3;
    }

    public void setStaticText3(StaticText st) {
        this.staticText3 = st;
    }

    private PasswordField txtConfPassword = new PasswordField();

    public PasswordField getTxtConfPassword() {
        return txtConfPassword;
    }

    public void setTxtConfPassword(PasswordField pf) {
        this.txtConfPassword = pf;
    }

    private HtmlPanelGrid gridPanel8 = new HtmlPanelGrid();

    public HtmlPanelGrid getGridPanel8() {
        return gridPanel8;
    }

    public void setGridPanel8(HtmlPanelGrid hpg) {
        this.gridPanel8 = hpg;
    }

    private PanelGroup groupPanel6 = new PanelGroup();

    public PanelGroup getGroupPanel6() {
        return groupPanel6;
    }

    public void setGroupPanel6(PanelGroup pg) {
        this.groupPanel6 = pg;
    }

    private StaticText staticText10 = new StaticText();

    public StaticText getStaticText10() {
        return staticText10;
    }

    public void setStaticText10(StaticText st) {
        this.staticText10 = st;
    }

    private ImageComponent image3 = new ImageComponent();

    public ImageComponent getImage3() {
        return image3;
    }

    public void setImage3(ImageComponent ic) {
        this.image3 = ic;
    }

    private StaticText staticText11 = new StaticText();

    public StaticText getStaticText11() {
        return staticText11;
    }

    public void setStaticText11(StaticText st) {
        this.staticText11 = st;
    }

    private StaticText staticText14 = new StaticText();

    public StaticText getStaticText14() {
        return staticText14;
    }

    public void setStaticText14(StaticText st) {
        this.staticText14 = st;
    }

    private Hyperlink lnkGerirUtilizadores = new Hyperlink();

    public Hyperlink getLnkGerirUtilizadores() {
        return lnkGerirUtilizadores;
    }

    public void setLnkGerirUtilizadores(Hyperlink h) {
        this.lnkGerirUtilizadores = h;
    }

    private StaticText staticText15 = new StaticText();

    public StaticText getStaticText15() {
        return staticText15;
    }

    public void setStaticText15(StaticText st) {
        this.staticText15 = st;
    }

    private Hyperlink lnkAnalisesAcidente = new Hyperlink();

    public Hyperlink getLnkAnalisesAcidente() {
        return lnkAnalisesAcidente;
    }

    public void setLnkAnalisesAcidente(Hyperlink h) {
        this.lnkAnalisesAcidente = h;
    }

    private Hyperlink lnkAjuda1 = new Hyperlink();

    public Hyperlink getLnkAjuda1() {
        return lnkAjuda1;
    }

    public void setLnkAjuda1(Hyperlink h) {
        this.lnkAjuda1 = h;
    }

    private StaticText staticText16 = new StaticText();

    public StaticText getStaticText16() {
        return staticText16;
    }

    public void setStaticText16(StaticText st) {
        this.staticText16 = st;
    }

    private StaticText staticText17 = new StaticText();

    public StaticText getStaticText17() {
        return staticText17;
    }

    public void setStaticText17(StaticText st) {
        this.staticText17 = st;
    }
    
    /**
     * <p>Construct a new Page bean instance.</p>
     */
    public FichaUtilizador() {
    }
    
    /**
     * <p>Callback method that is called whenever a page is navigated to,
     * either directly via a URL, or indirectly via page navigation.
     * Customize this method to acquire resources that will be needed
     * for event handlers and lifecycle methods, whether or not this
     * page is performing post back processing.</p>
     *
     * <p>Note that, if the current request is a postback, the property
     * values of the components do <strong>not</strong> represent any
     * values submitted with this request.  Instead, they represent the
     * property values that were saved for this view when it was rendered.</p>
     */
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here
        
        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("FichaUtilizador Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
        }
        
        // </editor-fold>
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here
	if (!getSessionBean1().isLoggedIn()) {
	    try {
		getExternalContext().redirect("Login.jsp");
	    } catch(Exception e) {  
	    // . . .  handle exception . . .              
	    }
	}
        else
        {
            
                if(
                   getSessionBean1().getCurrentUser().getTipo().intValue() == Global.TIPO_UTILIZADOR_DIRECTOR_GERAL_RH
                   || getSessionBean1().getCurrentUser().getTipo().intValue() == Global.TIPO_UTILIZADOR_DIRECTOR_SIPRP     )
                {
                    lnkGerirUtilizadores.setDisabled(false);
                }
                else
                {
                    lnkGerirUtilizadores.setDisabled(true);            
                }

               HttpServletRequest request = (HttpServletRequest) getExternalContext().getRequest();
               String referer = request.getRequestURI();
               String pageFrom = Utils.getPageFrom(referer);
               if(pageFrom.matches("FichaUtilizador.jsp"))
               {
                   isPostData = true;
               }
               if(!isPostData)
               {       


                   lblUser.setText( getSessionBean1().getCurrentUser().getLogin() );   
                   UtilizadoresDataProvider udp = new UtilizadoresDataProvider();

                   AnalisesDataProvider adp = new AnalisesDataProvider();
                   try
                   {
                        Integer permissao = udp.getPermissionCode( getSessionBean1().getCurrentUser().getId() );
                        getSessionBean1().setTiposOptions(adp.getTiposList(permissao));    
                        drpTipo.setSelected(new Integer(0));
                   }
                   catch(Exception ex)
                   {
                       ex.printStackTrace();
                   }            

                   try
                   {
                        getSessionBean1().setEstabelecimentosOptions(adp.getEstabelecimentosList( getSessionBean1().getCurrentUser().getEmpresa_id(), new Boolean(false) ));                           
                        drpEstabelecimentos.setSelected(new Integer(-1));
                   }
                   catch(Exception ex)
                   {
                       ex.printStackTrace();
                   }     

               } 
               else //postData
               {
                       String del_user = (String)getExternalContext().getRequestParameterMap().get("del_user");            
                       if(del_user != null)
                       {
                           if(del_user.matches("yes"))
                           {                
                               hidConfDelUser.setValue("");               
                               try
                               {
                                    deleteUser();                            
                               }
                               catch(Exception ex)
                               {
                                   ex.printStackTrace();
                                   getSessionBean1().setMsg("Erro na elimina&ccedil;&atilde;o do utilizador!");
                               }

                               //force a page reload
        //                        try
        //                        {
        //                            getExternalContext().redirect("FichaUtilizador.jsp");
        //                            System.out.println("REDIRECT");
        //                        }
        //                        catch(Exception ex)
        //                        {
        //                            ex.printStackTrace();
        //                        }

                           }
                           else if(del_user.matches("no"))
                           {
                               hidConfDelUser.setValue("");   
                               showUser();
                           }                   
                       }

               }            
            
        }
        

        
    }
    
    /**
     * <p>Callback method that is called after the component tree has been
     * restored, but before any event processing takes place.  This method
     * will <strong>only</strong> be called on a postback request that
     * is processing a form submit.  Customize this method to allocate
     * resources that will be required in your event handlers.</p>
     */
    public void preprocess() {
    }
    
    /**
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    public void prerender() {
        stCriarEditar.setText("EDITAR");         
        butApagar.setRendered(true);
        if(getSessionBean1().getModoEdicaoUtilizador().matches("new"))
        {
            if(!isPostData)
            {
                txtNome.setStyleClass("hide");
                stCriarEditar.setText("CRIAR");
                lblCap.setRendered(false);
                txtCap.setRendered(false);       
                lblCedula.setRendered(false);
                stCedula.setRendered(false);     
            }
            butApagar.setRendered(false);                                        
        }
       if(getSessionBean1().getModoEdicaoUtilizador().matches("edit"))           
       {
           //drpNome.setRendered(true); 
           butApagar.setRendered(false);
           if(!isPostData)
           {
                showUser();               
           }
       }        

        txtMsg.setText(getSessionBean1().getMsg());
       getSessionBean1().setMsg("");        
        
        if(getSessionBean1().isMudarPassword())
        {
            //txtMsg.setStyle("color: #000000; font-weight: bold");   
            if(!isPostData)
            {
                txtMsg.setText("Por favor confirme os seus dados e altere a password para uma apenas do seu conhecimento.");                            
            }
           //getSessionBean1().setMudarPassword(false);
        }
    }
    
    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    public void destroy() {
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     */
    protected SessionBean1 getSessionBean1() {
        return (SessionBean1)getBean("SessionBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     */
    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1)getBean("ApplicationBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     */
    protected RequestBean1 getRequestBean1() {
        return (RequestBean1)getBean("RequestBean1");
    }
    
    public String lnkAnalisesAcidente_action() {
        //return navigate();
        int tipo = getSessionBean1().getCurrentUser().getTipo().intValue();        
        if(tipo == Global.TIPO_UTILIZADOR_DIRECTOR_SIPRP)
        {
            return "form_dir_siprp";            
        }
        else if(tipo == Global.TIPO_UTILIZADOR_DIRECTOR_GERAL_RH)
        {
            return "form_dir_ger_rh";            
        }
        else if(tipo == Global.TIPO_UTILIZADOR_SEGURANCA)
        {
            return "form_seguranca";                        
        }
        else if(tipo == Global.TIPO_UTILIZADOR_RH)
        {
            return "form_rh";                        
        }
        else if(tipo == Global.TIPO_UTILIZADOR_RH)
        {
            return "form_rh";                        
        }
        else if(tipo == Global.TIPO_UTILIZADOR_HS)
        {
            return "form_hs";                        
        }
        else if(tipo == Global.TIPO_UTILIZADOR_GESTOR)
        {
            return "form_gestor";                        
        }
        
        return null;
    }    

    public String lnkLogout_action() {
        // TODO: Replace with your code
        try
        {
            javax.servlet.http.HttpSession session =
                    (javax.servlet.http.HttpSession) getExternalContext().getSession(true);
            session.invalidate();            
        }
        catch(Exception ex){}

	    try {
		getExternalContext().redirect("Login.jsp");
	    } catch(Exception e) {}        
        //return "login";	
        return null;
    }


    public String butCancelar_action() {
        // TODO: Process the button click action. Return value is a navigation
        // case name where null will return to the same page.
        
        return navigate();
    }

    public String butGravar_action() {
        // TODO: Process the button click action. Return value is a navigation
        // case name where null will return to the same page.
        if(validationOk())
        {
            if(getSessionBean1().getModoEdicaoUtilizador().matches("new"))
            {
                try
                {
                    Utilizador u = addUser();         
                    addPermissao(u);
                    getSessionBean1().setMsg("Utilizador criado");                    
                }
                catch(Exception ex)
                {
                    getSessionBean1().setMsg("Erro na cria&ccedil;&atilde;o do utilizador!");
                    ex.printStackTrace();
                }
            }
            else    //edit
            {
                try
                {
                    updateUser();   
                    //getSessionBean1().setMsg("Dados actualizados");                    
                    return navigate();
                }
                catch(Exception ex)
                {
                    getSessionBean1().setMsg("Erro na actualiza&ccedil;&atilde;o do utilizador");
                    ex.printStackTrace();                    
                }
            }
            
            if(getSessionBean1().isMudarPassword())
            {
                getSessionBean1().setMudarPassword(false);                
            }
            
        }
        
        return null;
    }

    public void drpTipo_processValueChange(ValueChangeEvent event) {
        // TODO: Replace with your code
        drpNome.setVisible(true);
        Integer tipo = (Integer) drpTipo.getSelected();
        boolean booGestor = false;
        if(tipo.intValue() == GESTOR)
        {
            booGestor = true;
        }
        AnalisesDataProvider adp = new AnalisesDataProvider();
        try
        {
            getSessionBean1().setEstabelecimentosOptions(adp.getEstabelecimentosList( getSessionBean1().getCurrentUser().getEmpresa_id(), new Boolean(booGestor) ));                           
            drpEstabelecimentos.setSelected(new Integer(-1));                    
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        if(tipo.intValue() == SEG || tipo.intValue() == RH || tipo.intValue() == GESTOR || tipo.intValue() == DIRECTOR_RH || tipo.intValue() == DIRECTOR_SIPRP)
        {
            drpNome.setRendered(false);
            txtNome.setStyleClass("show");                        
            lblCap.setRendered(false);
            txtCap.setRendered(false);       
            lblCedula.setRendered(false);
            stCedula.setRendered(false);     
        }
        else if(tipo.intValue() == HS || tipo.intValue() == MEDICO)
        {
            drpNome.setRendered(true);
            txtNome.setStyleClass("hide");                                   
            if(tipo.intValue() == HS)
            {
                lblCap.setRendered(true);
                txtCap.setRendered(true);
                lblCedula.setRendered(false);
                stCedula.setRendered(false);                
                try
                {
                    getSessionBean1().setMedicosOptions(adp.getTecnicosSaudeList());                           
                    drpNome.setSelected(new Integer(0));                    
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
            }
            else    // medicos
            {
                lblCedula.setRendered(true);
                stCedula.setRendered(true);
                lblCap.setRendered(false);
                txtCap.setRendered(false);                
                try
                {
                    getSessionBean1().setMedicosOptions(adp.getMedicosList());                           
                    drpNome.setSelected(new Integer(0));                                        
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();                    
                }                
            }
        }        
    }
    
    private boolean validationOk()
    {
        Integer tipo = (Integer) drpTipo.getSelected();
//        if(tipo.intValue() == 0)
//        {
//            getSessionBean1().setMsg("Tem de escolher um tipo!");
//            return false;
//        }
//        Integer estabelecimento = (Integer) drpEstabelecimentos.getSelected();
//        if(estabelecimento.intValue() == -1)
//        {
//            getSessionBean1().setMsg("Tem de escolher um estabelecimento!");
//            return false;
//        }
        
//        if(tipo.intValue() == SEG || tipo.intValue() == RH || tipo.intValue() == GESTOR || tipo.intValue() == DIRECTOR_RH || tipo.intValue() == DIRECTOR_SIPRP)
//        {
//            if(txtNome.getText() == null)
//            {
//                getSessionBean1().setMsg("Tem de indicar o nome!");
//                return false;
//            }
//            else
//            {
//                String nome = (String) txtNome.getText();                
//                if(nome.trim().length() == 0)
//                {
//                    getSessionBean1().setMsg("Tem de indicar o nome!");
//                    return false;
//                }
//            }
//        }
//        else if(tipo.intValue() == HS || tipo.intValue() == MEDICO)
//        {
//            Integer nome = (Integer) drpNome.getSelected();
//            if(nome.intValue() == 0)
//            {
//                getSessionBean1().setMsg("Tem de indicar o nome!");
//                return false;                
//            }
//        }
        
//        if(txtLogin.getText() == null)
//        {
//            getSessionBean1().setMsg("Tem de indicar o login!");            
//            return false;
//        }
//        else
//        {
//            String login = (String) txtLogin.getText();
//            if(login.trim().length() == 0)
//            {
//                getSessionBean1().setMsg("Tem de indicar o login!");    
//                return false;
//            }
//        }
        
        if(txtPassword.getText() == null)
        {
            getSessionBean1().setMsg("Tem de indicar a password!");            
            return false;
        }
        else
        {
            String password = (String) txtPassword.getText();
            if(password.trim().length() == 0)
            {
                getSessionBean1().setMsg("Tem de indicar a password!");    
                return false;
            }
            else
            {
                if(txtConfPassword.getText() == null)
                {
                    getSessionBean1().setMsg("Tem de confirmar a password!");    
                    return false;
                }
                else
                {
                    String conf_password = (String) txtConfPassword.getText();
                    if(conf_password.trim().length() == 0)
                    {
                        getSessionBean1().setMsg("Tem de confirmar a password!");    
                        return false;
                    }
                    else
                    {
                        if(!password.equals(conf_password))
                        {
                            getSessionBean1().setMsg("A confirma&ccedil;&atilde;o tem de ser igual &agrave; a password!");    
                            return false;                                
                        }
                    }
                }
            } //            
        }  
        
        if(getSessionBean1().isMudarPassword())
        {
            String password = (String) txtPassword.getText();        
            if(password.matches(getSessionBean1().getCurrentUser().getPassword()))
            {
                getSessionBean1().setMsg("A nova password tem de ser diferente da password actual!");
                return false;
            }
            
        }
        
//        if(tipo.intValue() == HS)
//        {
//            if(txtCap.getText() == null )
//            {
//                getSessionBean1().setMsg("Tem de indicar o c.a.p.!");            
//                return false;                
//            }
//            else
//            {
//                String cap = (String) txtCap.getText();
//                if(cap.trim().length() == 0)
//                {
//                    getSessionBean1().setMsg("Tem de indicar o c.a.p.!");    
//                    return false;
//                }                
//            }
//        }
        
        return true;
    }

    public void drpNome_processValueChange(ValueChangeEvent event) {
        // TODO: Replace with your code
        Integer tipo = (Integer) drpTipo.getSelected();
        if(tipo.intValue() == MEDICO)
        {
            AnalisesDataProvider adp = new AnalisesDataProvider();
            Integer medico_id = (Integer) drpNome.getSelected();
            try
            {
                String numero_cedula = adp.getNumeroCedula(medico_id);                
                stCedula.setText(numero_cedula);
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
    }
    
    private Utilizador addUser() throws Exception
    {
        Utilizador u = fillUser();
        UtilizadoresDataProvider udp = new UtilizadoresDataProvider();
        Integer id = udp.createNewUtilizador(u);
        u.setId(id);
        return u;
    }
    
    private void addPermissao(Utilizador u) throws Exception
    {
        Permissao p = new Permissao();
        p.setUser_id(u.getId());
        p.setCodigo_permissao(u.getTipo());
        UtilizadoresDataProvider udp = new UtilizadoresDataProvider();
        udp.createPermissao(p);
    }
    
    private void updateUser() throws Exception
    {
        Utilizador u = fillUser();
        u.setId(getSessionBean1().getCurrentUser().getId());
        UtilizadoresDataProvider udp = new UtilizadoresDataProvider();
        udp.updateUtilizador(u);        
    }   
    
    private void deleteUser() throws Exception
    {
        UtilizadoresDataProvider udp = new UtilizadoresDataProvider();
        udp.deleteUser(getSessionBean1().getCurrentUser().getId());
    }
    
    private void showUser()
    {
        AnalisesDataProvider adp = new AnalisesDataProvider();
        Utilizador u = getSessionBean1().getCurrentUser();
        drpTipo.setSelected(u.getTipo());
        if(u.getTipo().intValue() == SEG || u.getTipo().intValue() == RH || u.getTipo().intValue() == HS || u.getTipo().intValue() == MEDICO || u.getTipo().intValue() == GESTOR || u.getTipo().intValue() == DIRECTOR_RH || u.getTipo().intValue() == DIRECTOR_SIPRP)
        {
            drpNome.setRendered(false);
            txtNome.setStyleClass("show");
            lblCap.setRendered(false);
            txtCap.setRendered(false);       
            lblCedula.setRendered(false);
            stCedula.setRendered(false);    
            txtNome.setText(utils.Utils.unicodeToHTML(u.getNome()));
        }
        else if(u.getTipo().intValue() == HS)
        {
            //txtNome.setRendered(false);      
            try
            {
                getSessionBean1().setMedicosOptions(adp.getTecnicosSaudeList());                           
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }            
            drpNome.setSelected(u.getFuncionario_hst_id());            
            drpNome.setStyleClass("show");
            lblCap.setRendered(true);
            txtCap.setRendered(true);    
            lblCedula.setRendered(false);
            stCedula.setRendered(false);       
            txtCap.setText(u.getCap());
        }
        else if(u.getTipo().intValue()  == MEDICO)  //medico
        {
            drpNome.setRendered(true);
            try
            {
                getSessionBean1().setMedicosOptions(adp.getMedicosList());                           
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }                        
            drpNome.setSelected(u.getMedico_id());            
            txtNome.setStyleClass("hide");  
            lblCap.setRendered(false);
            txtCap.setRendered(false);                
            lblCedula.setRendered(true);
            stCedula.setRendered(true);       
            stCedula.setText(u.getNumero_cedula());

        }
        if(u.getEstabelecimento_id() != null)
        {
            drpEstabelecimentos.setSelected(u.getEstabelecimento_id());             
        }

        txtLogin.setText(u.getLogin());
        //txtPassword.setText(u.getPassword());
        txtEmail.setText(u.getEmail());
    }
    
    private Utilizador fillUser()
    {
        //Utilizador u = new Utilizador();
        Utilizador u = getSessionBean1().getCurrentUser();
//        u.setActivo("y");
//        u.setAdministrador("n");
//        u.setTipo((Integer) drpTipo.getSelected());
//        u.setEmpresa_id(getSessionBean1().getCurrentUser().getEmpresa_id());
//        u.setEstabelecimento_id( (Integer) drpEstabelecimentos.getSelected() );
//        u.setLogin( (String) txtLogin.getText() );
        String password = (String) txtPassword.getText();
        u.setPassword( password );
        java.util.Date today =
                        new java.util.Date();
        java.sql.Date sqlToday =
                        new java.sql.Date(today.getTime());          
        u.setData_password(sqlToday);


        u.setEmail("");
        if(txtEmail.getText() != null)
        {
            u.setEmail( (String) txtEmail.getText() );
        }
        
        Integer tipo = (Integer) drpTipo.getSelected();
        
//        u.setNumero_cedula("");
//        u.setCap("");
//        if(tipo.intValue()  == HS || tipo.intValue()  == MEDICO)
//        {
//            AnalisesDataProvider adp = new AnalisesDataProvider();
//            if(tipo.intValue()  == HS)
//            {
//                try
//                {
//                    Integer tecnico_id = (Integer) drpNome.getSelected();
//                    u.setFuncionario_hst_id(tecnico_id);
//                    u.setNome( adp.getTecnicoSaudeNome(tecnico_id) );
//                }
//                catch(Exception ex)
//                {
//                    ex.printStackTrace();
//                }
//                u.setCap( (String) txtCap.getText());
//            }
//            else  // medico
//            {
//                try
//                {
//                    Integer medico_id = (Integer) drpNome.getSelected();
//                    u.setMedico_id(medico_id);
//                    u.setNome( adp.getMedicoNome(medico_id) );
//                }
//                catch(Exception ex)
//                {
//                    ex.printStackTrace();
//                }                
//                u.setNumero_cedula( (String) stCedula.getText());
//            }
//        }
//        else
//        {
//            u.setNome( (String) txtNome.getText() );
//        } 
        
//        u.setResponsavel_loja("n");        
//        if(chkResponsavelLoja.getSelected() != null)
//        {
//            if(chkResponsavelLoja.getSelected().equals(new Boolean(true)))
//            {
//                u.setResponsavel_loja("y");                        
//            }
//        }
//        
//        if(u.getGestor_geral() == null)
//        {
//            u.setGestor_geral("n");
//        }
        
        u.setPrimeiro_login("n");
        return u;
    }

    public String lnkEditUser_action() {
        // TODO: Replace with your code
        
        getSessionBean1().setModoEdicaoUtilizador("edit");
        return "user";
    }

    public String butApagar_action() {
        // TODO: Replace with your code
        hidConfDelUser.setValue("apagar");                            
        return null;
    }
    
    private String navigate()
    {
        String nav_from = getSessionBean1().getNavFrom();
        if(nav_from.matches("FormSeguranca"))
        {
            return "form_seguranca";
        }
        else if(nav_from.matches("FormRH"))
        {
            return "form_rh";
        }
        else if(nav_from.matches("FormHS"))
        {
            return "form_hs";
        }
        else if(nav_from.matches("FormMedico"))
        {
            return "form_medico";
        }        
        else if(nav_from.matches("AnaliseAcidenteTrabalho"))
        {
            return "analise_acidente";
        }
        else if(nav_from.matches("ViewAnaliseAcidenteTrabalho"))
        {
            return "view_analise";
        }
        else if(nav_from.matches("FormGestor"))
        {
            return "form_gestor";
        }                
        else if(nav_from.matches("FormDirGerRh"))
        {
            return "form_dir_ger_rh";
        }                
        else if(nav_from.matches("FormDirSiprp"))
        {
            return "form_dir_siprp";
        }        
        else if(nav_from.matches("GestaoUtilizadores"))
        {
            return "gestao_utilizadores";
        }        
        else if(nav_from.matches("NovoUtilizador"))
        {
            return "novo_utilizador";
        }        
        else if(nav_from.matches("Login")) // first login
        {
            int tipo = getSessionBean1().getCurrentUser().getTipo().intValue();
            switch(tipo)
            {
                case Global.TIPO_UTILIZADOR_SEGURANCA:
                    return "form_seguranca";
                case Global.TIPO_UTILIZADOR_RH:
                    return "form_rh";                    
                case Global.TIPO_UTILIZADOR_HS:
                    return "form_hs";                    
                case Global.TIPO_UTILIZADOR_MEDICO:
                    return "form_medico";                    
                case Global.TIPO_UTILIZADOR_GESTOR:
                    return "form_gestor";                    
                case Global.TIPO_UTILIZADOR_DIRECTOR_GERAL_RH:
                    return "form_dir_ger_rh";                    
                case Global.TIPO_UTILIZADOR_DIRECTOR_SIPRP:
                    return "form_dir_siprp";                                        
            }
        }                
        return null;
    }

    public String lnkNewUser_action() {
        // TODO: Replace with your code

        if(getSessionBean1().getCurrentUser().getTipo().intValue() == Global.TIPO_UTILIZADOR_DIRECTOR_GERAL_RH)
        {
            getSessionBean1().setNavFrom("FormDirGerRh");                    
        }
        else if(getSessionBean1().getCurrentUser().getTipo().intValue() == Global.TIPO_UTILIZADOR_DIRECTOR_SIPRP)
        {
            getSessionBean1().setNavFrom("FormDirSiprp");                    
        }
        

        return "gestao_utilizadores";

    }

    public String lnkAjuda_action() {
        // TODO: Replace with your code
//        ServletContext theApplicationsServletContext =
//             (ServletContext) this.getExternalContext().getContext();
//         String pdfFolderPath = theApplicationsServletContext.getRealPath(Global.PDF_FOLDER_URL); 
//         String pdfFilePath = pdfFolderPath + "/Ajuda.pdf";  
//         
//         Global global = new Global();
//         try
//         {
//            global.showPdf(pdfFilePath);
//         }
//         catch(Exception ex)
//         {
//             ex.printStackTrace();
//         }                
        return null;
    }
}

