/*
 * UtilizadorFields.java
 *
 * Created on December 4, 2007, 3:27 PM
 * 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 db.AnalisesDataProvider;
import db.UtilizadoresDataProvider;
import global.Global;
import javax.faces.FacesException;
import javax.faces.component.html.HtmlPanelGrid;
import javax.faces.event.ValueChangeEvent;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import utils.Utils;

/**
 * <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 UtilizadorFields 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 lnkEditUser1 = new Hyperlink();

    public Hyperlink getLnkEditUser1() {
        return lnkEditUser1;
    }

    public void setLnkEditUser1(Hyperlink h) {
        this.lnkEditUser1 = h;
    }

    private StaticText staticText2 = new StaticText();

    public StaticText getStaticText2() {
        return staticText2;
    }

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

    private Hyperlink lnkLogout1 = new Hyperlink();

    public Hyperlink getLnkLogout1() {
        return lnkLogout1;
    }

    public void setLnkLogout1(Hyperlink h) {
        this.lnkLogout1 = 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 staticText3 = new StaticText();

    public StaticText getStaticText3() {
        return staticText3;
    }

    public void setStaticText3(StaticText st) {
        this.staticText3 = 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 staticText10 = new StaticText();

    public StaticText getStaticText10() {
        return staticText10;
    }

    public void setStaticText10(StaticText st) {
        this.staticText10 = 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 HtmlPanelGrid gridPanel4 = new HtmlPanelGrid();

    public HtmlPanelGrid getGridPanel4() {
        return gridPanel4;
    }

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

    private StaticText staticText4 = new StaticText();

    public StaticText getStaticText4() {
        return staticText4;
    }

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

    private HtmlPanelGrid gridPanel5 = new HtmlPanelGrid();

    public HtmlPanelGrid getGridPanel5() {
        return gridPanel5;
    }

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

    private PanelGroup groupPanel6 = new PanelGroup();

    public PanelGroup getGroupPanel6() {
        return groupPanel6;
    }

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

    private PanelGroup groupPanel7 = new PanelGroup();

    public PanelGroup getGroupPanel7() {
        return groupPanel7;
    }

    public void setGroupPanel7(PanelGroup pg) {
        this.groupPanel7 = pg;
    }

    private StaticText staticText5 = new StaticText();

    public StaticText getStaticText5() {
        return staticText5;
    }

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

    private StaticText staticText8 = new StaticText();

    public StaticText getStaticText8() {
        return staticText8;
    }

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

    private HtmlPanelGrid gridPanel8 = new HtmlPanelGrid();

    public HtmlPanelGrid getGridPanel8() {
        return gridPanel8;
    }

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

    private DropDown drpEstabelecimentos = new DropDown();

    public DropDown getDrpEstabelecimentos() {
        return drpEstabelecimentos;
    }

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

    private StaticText stEstabelecimento = new StaticText();

    public StaticText getStEstabelecimento() {
        return stEstabelecimento;
    }

    public void setStEstabelecimento(StaticText st) {
        this.stEstabelecimento = st;
    }

    private StaticText staticText11 = new StaticText();

    public StaticText getStaticText11() {
        return staticText11;
    }

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

    private HtmlPanelGrid gridPanel9 = new HtmlPanelGrid();

    public HtmlPanelGrid getGridPanel9() {
        return gridPanel9;
    }

    public void setGridPanel9(HtmlPanelGrid hpg) {
        this.gridPanel9 = 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 stNome = new StaticText();

    public StaticText getStNome() {
        return stNome;
    }

    public void setStNome(StaticText st) {
        this.stNome = st;
    }

    private StaticText staticText13 = new StaticText();

    public StaticText getStaticText13() {
        return staticText13;
    }

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

    private TextField txtLogin = new TextField();

    public TextField getTxtLogin() {
        return txtLogin;
    }

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

    private StaticText staticText14 = new StaticText();

    public StaticText getStaticText14() {
        return staticText14;
    }

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

    private PasswordField txtPassword = new PasswordField();

    public PasswordField getTxtPassword() {
        return txtPassword;
    }

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

    private StaticText staticText15 = new StaticText();

    public StaticText getStaticText15() {
        return staticText15;
    }

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

    private TextField txtEmail = new TextField();

    public TextField getTxtEmail() {
        return txtEmail;
    }

    public void setTxtEmail(TextField tf) {
        this.txtEmail = tf;
    }
    
    // </editor-fold>
    boolean isPostback = false;        

    private HiddenField hidConfDelUser = new HiddenField();

    public HiddenField getHidConfDelUser() {
        return hidConfDelUser;
    }

    public void setHidConfDelUser(HiddenField hf) {
        this.hidConfDelUser = hf;
    }

    private StaticText staticText7 = new StaticText();

    public StaticText getStaticText7() {
        return staticText7;
    }

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

    private PasswordField txtConfPassword = new PasswordField();

    public PasswordField getTxtConfPassword() {
        return txtConfPassword;
    }

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

    private StaticText stTipo = new StaticText();

    public StaticText getStTipo() {
        return stTipo;
    }

    public void setStTipo(StaticText st) {
        this.stTipo = st;
    }

    private HtmlPanelGrid gridPanel10 = new HtmlPanelGrid();

    public HtmlPanelGrid getGridPanel10() {
        return gridPanel10;
    }

    public void setGridPanel10(HtmlPanelGrid hpg) {
        this.gridPanel10 = hpg;
    }

    private PanelGroup groupPanel8 = new PanelGroup();

    public PanelGroup getGroupPanel8() {
        return groupPanel8;
    }

    public void setGroupPanel8(PanelGroup pg) {
        this.groupPanel8 = pg;
    }

    private Checkbox chkActivo = new Checkbox();

    public Checkbox getChkActivo() {
        return chkActivo;
    }

    public void setChkActivo(Checkbox c) {
        this.chkActivo = c;
    }

    private StaticText staticText6 = new StaticText();

    public StaticText getStaticText6() {
        return staticText6;
    }

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

    private StaticText staticText9 = new StaticText();

    public StaticText getStaticText9() {
        return staticText9;
    }

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

    private StaticText lblRespLoja = new StaticText();

    public StaticText getLblRespLoja() {
        return lblRespLoja;
    }

    public void setLblRespLoja(StaticText st) {
        this.lblRespLoja = st;
    }

    private Checkbox chkRespLoja = new Checkbox();

    public Checkbox getChkRespLoja() {
        return chkRespLoja;
    }

    public void setChkRespLoja(Checkbox c) {
        this.chkRespLoja = c;
    }

    private StaticText lblGeral = new StaticText();

    public StaticText getLblGeral() {
        return lblGeral;
    }

    public void setLblGeral(StaticText st) {
        this.lblGeral = st;
    }

    private Checkbox chkGeral = new Checkbox();

    public Checkbox getChkGeral() {
        return chkGeral;
    }

    public void setChkGeral(Checkbox c) {
        this.chkGeral = c;
    }

    private HtmlPanelGrid gridPanel11 = new HtmlPanelGrid();

    public HtmlPanelGrid getGridPanel11() {
        return gridPanel11;
    }

    public void setGridPanel11(HtmlPanelGrid hpg) {
        this.gridPanel11 = hpg;
    }

    private PanelGroup groupPanel9 = new PanelGroup();

    public PanelGroup getGroupPanel9() {
        return groupPanel9;
    }

    public void setGroupPanel9(PanelGroup pg) {
        this.groupPanel9 = pg;
    }

    private StaticText staticText12 = new StaticText();

    public StaticText getStaticText12() {
        return staticText12;
    }

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

    private ImageComponent image3 = new ImageComponent();

    public ImageComponent getImage3() {
        return image3;
    }

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

    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;
    }

    private Hyperlink lnkNewUser1 = new Hyperlink();

    public Hyperlink getLnkNewUser1() {
        return lnkNewUser1;
    }

    public void setLnkNewUser1(Hyperlink h) {
        this.lnkNewUser1 = h;
    }

    private StaticText staticText18 = new StaticText();

    public StaticText getStaticText18() {
        return staticText18;
    }

    public void setStaticText18(StaticText st) {
        this.staticText18 = st;
    }

    private Hyperlink lnkAnalisesAcidente = new Hyperlink();

    public Hyperlink getLnkAnalisesAcidente() {
        return lnkAnalisesAcidente;
    }

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

    private Hyperlink lnkAjuda = new Hyperlink();

    public Hyperlink getLnkAjuda() {
        return lnkAjuda;
    }

    public void setLnkAjuda(Hyperlink h) {
        this.lnkAjuda = h;
    }

    private StaticText staticText19 = new StaticText();

    public StaticText getStaticText19() {
        return staticText19;
    }

    public void setStaticText19(StaticText st) {
        this.staticText19 = st;
    }
    /**
     * <p>Construct a new Page bean instance.</p>
     */
    public UtilizadorFields() {
    }
    
    /**
     * <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("UtilizadorFields 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
        {
            
            lblUser.setText( getSessionBean1().getCurrentUser().getLogin() );         
           HttpServletRequest request = (HttpServletRequest) getExternalContext().getRequest();
           String referer = request.getRequestURI();
           String pageFrom = Utils.getPageFrom(referer);
           if(!pageFrom.matches("UtilizadorFields.jsp"))        
           {
               isPostback = false;
           }
           else
           {
               isPostback = true;
           }                            
            
        }

    }
    
    /**
     * <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() {
        if(!isPostback)
        {
            if(getSessionBean1().getModoEdicaoUtilizador().matches("new"))
            {
                stCriarEditar.setText("CRIAR");
                butApagar.setRendered(false);
                initializeNew();                
            }
            else if( getSessionBean1().getModoEdicaoUtilizador().matches("edit"))
            {
                stCriarEditar.setText("EDITAR");                
                fillPage();
            }
        }
        else    //postback
        {
           String del_user = (String)getExternalContext().getRequestParameterMap().get("del_user");            
           if(del_user != null)
           {
               if(del_user.matches("yes"))
               {                
                   hidConfDelUser.setValue("");               
                   try
                   {
                        deleteUser(); 
                        getSessionBean1().setMsg("Utilizador eliminado!"); 
                        //return "gestao_utilizadores";       
                        getSessionBean1().setUserDeleted(true);
                        try {
                            getExternalContext().redirect("GestaoUtilizadores.jsp");
                        } catch(Exception e) {  
                        }
                   }
                   catch(Exception ex)
                   {
                       ex.printStackTrace();
                       getSessionBean1().setMsg("Erro na elimina&ccedil;&atilde;o do utilizador!");
                   }
               }
               else if(del_user.matches("no"))
               {
                   hidConfDelUser.setValue("");   
                   fillPage();
               }                   
           }
            
        }
        
        txtMsg.setText(getSessionBean1().getMsg());
        getSessionBean1().setMsg("");
        
    }
    
    /**
     * <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 ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1)getBean("ApplicationBean1");
    }

    /**
     * <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 RequestBean1 getRequestBean1() {
        return (RequestBean1)getBean("RequestBean1");
    }

    public String lnkEditUser_action() {
        // TODO: Replace with your code
        
        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 null;	

    }

    public void drpTipo_processValueChange(ValueChangeEvent event) {
        // TODO: Replace with your code
        
    }

    public void drpNome_processValueChange(ValueChangeEvent event) {
        // TODO: Replace with your code
        
    }

    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.
        String nav_from = getSessionBean1().getNavFrom();
        if(nav_from.matches("GestaoUtilizadores"))
        {
            return "gestao_utilizadores";
        }
        else if(nav_from.matches("NovoUtilizador"))
        {
            return "novo_utilizador";            
        }
        return null;
    }

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

    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( getSessionBean1().getModoEdicaoUtilizador() ))
        {
            if(getSessionBean1().getModoEdicaoUtilizador().matches("new"))
            {
                try
                {
                    Utilizador u = addUser();         
                    addPermissao(u);
                    getSessionBean1().setMsg("Utilizador criado");  
                    getSessionBean1().setNewUser(null);
                    return "gestao_utilizadores";
                }
                catch(Exception ex)
                {
                    getSessionBean1().setMsg("Erro na cria&ccedil;&atilde;o do utilizador!");
                    ex.printStackTrace();
                }
            }
            else if( getSessionBean1().getModoEdicaoUtilizador().matches("edit") )
            {
                try
                {
                    updateUser();     
                    getSessionBean1().setMsg("Utilizador actualizado");     
                    return "gestao_utilizadores";                    
                }
                catch(Exception ex)
                {
                    getSessionBean1().setMsg("Erro na actualiza&ccedil;&atilde;o do utilizador");
                    ex.printStackTrace();                    
                }                
            }
        }
        return null;
    }
    
    private void initializeNew()
    {
        //drpTipo.setStyleClass("hidden");
        //drpEstabelecimentos.setStyleClass("hidden");
        NewUser u = getSessionBean1().getNewUser();
        if(u.getEstabelecimento() == null)
        {
            drpEstabelecimentos.setDisabled(true);
        }
        else
        {
            drpEstabelecimentos.setSelected(u.getEstabelecimento());                    
        }

        drpNome.setStyleClass("hidden");
        txtNome.setStyleClass("hidden");
        

        stTipo.setText(u.getTipo_descricao());
        //stEstabelecimento.setText(u.getEstabelecimento_descricao());
        stEstabelecimento.setStyleClass("hidden");        
        stNome.setText(Utils.unicodeToHTML(u.getNome()));
        
        txtLogin.setText("");
        txtPassword.setText("");
        txtConfPassword.setText("");
        txtEmail.setText("");
        
        
        chkActivo.setSelected(new Boolean(true));
        lblGeral.setRendered(false);
        chkGeral.setRendered(false);
        lblRespLoja.setRendered(false);
        chkRespLoja.setRendered(false);
    }
    
    private void fillPage()
    {
        UtilizadoresDataProvider udp = new UtilizadoresDataProvider();
        AnalisesDataProvider adp = new AnalisesDataProvider();
        try
        {
            //Integer permissao = udp.getPermissionCode( getSessionBean1().getCurrentUser().getId() );        
            //getSessionBean1().setTiposOptions(adp.getTiposList(permissao));                      
            getSessionBean1().setTiposOptions(adp.getTiposList());                                  
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }

        Utilizador u = getSessionBean1().getEditUser();
        //stTipo.setStyleClass("hidden");
        stEstabelecimento.setStyleClass("hidden");
        stNome.setStyleClass("hidden");
        
        System.out.println("ACTIVO = " + u.getActivo());
        if(u.getActivo().matches("y"))
        {
            chkActivo.setSelected(new Boolean(true));
        }
        else
        {
            chkActivo.setSelected(new Boolean(false));            
        }
        //drpTipo.setSelected(u.getTipo());
        try
        {
            stTipo.setText(adp.getTipoDescricao(u.getTipo()));
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        drpEstabelecimentos.setSelected(u.getEstabelecimento_id());
        
        if(u.getTipo().intValue() == 3) //hs
        {
            drpNome.setStyleClass("hidden");
            txtNome.setText(Utils.unicodeToHTML(u.getNome()));            
        }
        else if(u.getTipo().intValue() == 5)  //medico
        {
            drpNome.setStyleClass("hidden");    
            System.out.println("MEDICA : " + Utils.unicodeToHTML(u.getNome()));
            txtNome.setText(Utils.unicodeToHTML(u.getNome()));  
        }
        else
        {
            drpNome.setStyleClass("hidden");
            txtNome.setText(Utils.unicodeToHTML(u.getNome()));  
        }
        
        if(u.getTipo().intValue() == 6) // gestor
        {
            chkGeral.setSelected(new Boolean(false));            
            if(u.getGestor_geral().matches("y"))
            {
                chkGeral.setSelected(new Boolean(true));
            }
        }
        else
        {
            lblGeral.setRendered(false);
            chkGeral.setRendered(false);
        }
        
        
        if(u.getTipo().intValue() == 1 || u.getTipo().intValue() == 2)
        {
            chkRespLoja.setSelected(new Boolean(false));            
            if(u.getResponsavel_loja().matches("y"))
            {
                chkRespLoja.setSelected(new Boolean(true));
            }
        }
        else
        {
            lblRespLoja.setRendered(false);
            chkRespLoja.setRendered(false);
        }
        
        txtLogin.setText(u.getLogin());
        //txtPassword.setText(u.getPassword());
        txtEmail.setText(u.getEmail());
        
    }   
    
    private boolean validationOk(String modo)
    {
        if(modo.matches("new"))
        {
            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;
                }
                else
                {
                    UtilizadoresDataProvider udp = new UtilizadoresDataProvider();
                    try
                    {
                        Utilizador u = udp.getUtilizador(login);
                        if(u.getLogin().equals(login))
                        {
                            getSessionBean1().setMsg("O utilizador " + login + " já existe!");    
                            return false;                            
                        }
                    }
                    catch(Exception ex)
                    {
                        ex.printStackTrace();
                    }
                }
            }

            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(txtEmail.getText() != null)
            {
                String email = (String) txtEmail.getText();
                if(email.trim().length() > 0)
                {
                    if(! Utils.isValidEmail(email))
                    {
                        getSessionBean1().setMsg("Email inv&aacute;lido!");
                        return false;
                    }
                    
                }
                else
                {
                    getSessionBean1().setMsg("Tem de indicar o email!");            
                    return false;
                }
            }
            else
            {
                getSessionBean1().setMsg("Tem de indicar o email!");            
                return false;
            }
            
        }
        else if(modo.matches("edit"))
        {
            Utilizador u = getSessionBean1().getEditUser();
            
//            Integer iTipo = (Integer) drpTipo.getSelected();
//            if(iTipo.intValue() == 0)
//            {
//                getSessionBean1().setMsg("Falta tipo !");
//                return false;
//            }
            
            int tipo = u.getTipo().intValue();
            
            if(tipo != 3)
            {
                Integer estabelecimento = (Integer) drpEstabelecimentos.getSelected();
                if(estabelecimento.intValue() == -1)
                {
                    getSessionBean1().setMsg("Falta estabelecimento!");
                    return false;
                }
            }

//            if(tipo == 3 || tipo == 5)
//            {
//                Integer nome = (Integer) drpNome.getSelected();
//                if(nome.intValue() == 0)
//                {
//                    getSessionBean1().setMsg("Falta nome !");
//                    return false;
//                }
//            }
//            else
//            {
                if(txtNome.getText() == null)
                {
                    getSessionBean1().setMsg("Falta nome!");
                    
                    return false;
                }
                else
                {
                    String nome = (String) txtNome.getText();
                    if(nome.trim().length() == 0)
                    {
                        getSessionBean1().setMsg("Falta 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;
                    }
                    else
                    {
                        if(!login.equals(u.getLogin()))
                        {
                            UtilizadoresDataProvider udp = new UtilizadoresDataProvider();
                            try
                            {
                                Utilizador ut = udp.getUtilizador(login);
                                if(ut.getLogin().equals(login))
                                {
                                    getSessionBean1().setMsg("O utilizador " + login + " já existe!");    
                                    return false;                            
                                }
                            }
                            catch(Exception ex)
                            {
                                ex.printStackTrace();
                            }                            
                        }

                    }
                }
//              if(txtPassword.getText() == null)
//              {
//                    getSessionBean1().setMsg("Falta password!");
//                    return false;                
//              }
//              else
              if(txtPassword.getText() != null)
              {
                    String password = (String) txtPassword.getText();
                    if(password.trim().length() > 0)
                    {
                        if(! password.equals(u.getPassword()))
                        {
                            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; password!");    
                                        return false;                                
                                    }
                                }                                
                            }
                        }                        
                    }
                    else
                    {
                        if(txtConfPassword.getText() != null)
                        {
                            String conf = (String) txtConfPassword.getText();
                            if(conf.trim().length() > 0)
                            {
                                getSessionBean1().setMsg("Falta password!");                            
                                return false;
                            }
                        }
                    }
              }
              else
              {
                    if(txtConfPassword.getText() != null)
                    {
                        String conf = (String) txtConfPassword.getText();
                        if(conf.trim().length() > 0)
                        {
                            getSessionBean1().setMsg("Falta password!");                            
                            return false;
                        }
                    }
              }
            
            if(txtEmail.getText() != null)
            {
                String email = (String) txtEmail.getText();
                if(email.trim().length() > 0)
                {
                    if(! Utils.isValidEmail(email))
                    {
                        getSessionBean1().setMsg("Email inv&aacute;lido!");
                        return false;
                    }
                    
                }
            }   
            else
            {
                getSessionBean1().setMsg("Tem de indicar o email!");            
                return false;
            }
            
        }
        return true;
    }
    
    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
    {
        AnalisesDataProvider adp = new AnalisesDataProvider();
        //Utilizador u = fillUser();
        Utilizador u = getSessionBean1().getEditUser();
        
        
        //u.setTipo((Integer) drpTipo.getSelected());
        u.setEstabelecimento_id( (Integer) drpEstabelecimentos.getSelected() );
        
        int tipo = u.getTipo().intValue();
//        if(tipo == 3)
//        {
//            u.setFuncionario_hst_id((Integer) drpNome.getSelected());
//            u.setNome( adp.getTecnicoSaudeNome( u.getFuncionario_hst_id() ) );
//        }
//        else if(tipo == 5)
//        {
//            u.setMedico_id( (Integer) drpNome.getSelected() );
//            u.setNome( adp.getMedicoNome(u.getMedico_id()) );
//        }
        u.setActivo("n");        
        if(chkActivo.getSelected() != null)
        {
            if(chkActivo.getSelected().equals(new Boolean(true)))
            {
                u.setActivo("y");                        
            }
        }        
        u.setNome((String) txtNome.getText());
        u.setLogin((String) txtLogin.getText());
        if(txtPassword.getText() != null)
        {
            String password = (String) txtPassword.getText();
            if(password.trim().length() > 0)
            {
                u.setPassword(password);                
            }
        }

        u.setEmail((String) txtEmail.getText());
        
        u.setGestor_geral("n");
        try
        {
            if(chkGeral.getSelected() != null)
            {
                if(chkGeral.getSelected().equals(new Boolean(true)) )
                {
                    u.setGestor_geral("y");
                }
            }
        }
        catch(Exception ex){}
        
        u.setResponsavel_loja("n");
        try
        {
            if(chkRespLoja.getSelected() != null)
            {
                if(chkRespLoja.getSelected().equals(new Boolean(true)) )
                {
                    u.setResponsavel_loja("y");
                }
            }
        }        
        catch(Exception ex){}
        u.setPrimeiro_login("n");
        UtilizadoresDataProvider udp = new UtilizadoresDataProvider();
        udp.updateUtilizador(u);        
    }   
    
    
    private Utilizador fillUser()
    {
        NewUser nu = getSessionBean1().getNewUser();
        Utilizador u = new Utilizador();
        u.setActivo("n");        
        if(chkActivo.getSelected() != null)
        {
            if(chkActivo.getSelected().equals(new Boolean(true)))
            {
                u.setActivo("y");                        
            }
        }
        u.setAdministrador("n");
        u.setTipo(nu.getTipo());
        u.setEmpresa_id(getSessionBean1().getCurrentUser().getEmpresa_id());
        //u.setEstabelecimento_id( nu.getEstabelecimento() );
        if(nu.getEstabelecimento() != null)
        {
            u.setEstabelecimento_id((Integer) drpEstabelecimentos.getSelected());
        }
        u.setNome(Utils.unicodeToHTML(nu.getNome()));
        u.setLogin( (String) txtLogin.getText() );
        u.setPassword( (String) txtPassword.getText() );
        java.util.Date today =
                        new java.util.Date();
        java.sql.Date sqlToday =
                        new java.sql.Date(today.getTime());          
        u.setData_password(sqlToday);        
        u.setEmail("");
        u.setNumero_mecanografico(nu.getNumero_mecanografico());
        if(txtEmail.getText() != null)
        {
            u.setEmail( (String) txtEmail.getText() );
        }
        
        Integer tipo = (Integer) nu.getTipo();
        
        u.setNumero_cedula("");
        u.setCap("");
        if(tipo.intValue()  == 3 || tipo.intValue()  == 5)
        {
            AnalisesDataProvider adp = new AnalisesDataProvider();
            if(tipo.intValue()  == 3)
            {
                try
                {
                    //Integer tecnico_id = (Integer) drpNome.getSelected();
                    //u.setFuncionario_hst_id(tecnico_id);
                    //u.setNome( adp.getTecnicoSaudeNome(tecnico_id) );
                    u.setFuncionario_hst_id(nu.getFuncionario_hst_id());
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
                u.setCap( nu.getCap());
            }
            else  // medico
            {
                try
                {
                    //Integer medico_id = (Integer) drpNome.getSelected();
                    //u.setMedico_id(medico_id);
                    //u.setNome( adp.getMedicoNome(medico_id) );
                    u.setMedico_id(nu.getMedico_id());
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }                
                //u.setNumero_cedula( (String) stCedula.getText());
                u.setNumero_cedula(nu.getNumero_cedula());
            }
        }
//        else
//        {
//            u.setNome( (String) txtNome.getText() );
//        } 
        
        u.setResponsavel_loja(nu.getResponsavel_loja());
        if(nu.getGestor_geral() == null)
        {
            u.setGestor_geral("n");
        }
        else
        {
            u.setGestor_geral(nu.getGestor_geral());            
        }

        
//        u.setResponsavel_loja("n");        
//        if(chkResponsavelLoja.getSelected() != null)
//        {
//            if(chkResponsavelLoja.getSelected().equals(new Boolean(true)))
//            {
//                u.setResponsavel_loja("y");                        
//            }
//        }
        return u;
    }   
    
    private void deleteUser() throws Exception
    {
        UtilizadoresDataProvider udp = new UtilizadoresDataProvider();
        udp.deleteUser(getSessionBean1().getEditUser().getId());
    }    

    public String lnkNewUser_action() {
        // TODO: Replace with your code
        
        return null;
    }

    public String lnkAnalisesAcidente_action() {
        // TODO: Replace with your code
        Integer tipo_utilizador = getSessionBean1().getCurrentUser().getTipo();
        if(tipo_utilizador.intValue() == Global.TIPO_UTILIZADOR_DIRECTOR_SIPRP)
        {
            return "form_dir_siprp";            
        }
        else if(tipo_utilizador.intValue() == Global.TIPO_UTILIZADOR_DIRECTOR_GERAL_RH)
        {
            return "form_dir_ger_rh";                        
        }
        
        return null;
    }

    public void drpEstabelecimentos_processValueChange(ValueChangeEvent event) {
        // TODO: Replace with your code
        
    }

    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;
    }
}

