package vut.msa.managedBeans;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.apache.log4j.Logger;
import vut.msa.helpers.UsersHelper;
import vut.msa.pojos.User;

/**
 * Trieda typu JavaBean pre pracu s uzivatelmi.
 */
public class UserBean {

    private static Logger log = Logger.getLogger(UserBean.class);

    private User user;
    private UsersHelper uHelper;

    public UserBean() {
        this.uHelper = new UsersHelper();
        this.user = new User();
    }

    //PROPERTY: user
    public User getUser() { return user; }
    public void setUser(User user) { this.user = user; }

    /**
     * Metoda vytvori noveho uzivatela systemu a ulozi udaje do databazy.
     * Udaje si nacita z formulara.
     *
     * @param event udalost stlacenia tlacidla pre vytvorenie uzivatela
     */
    public void addUser(ActionEvent event) {

        FacesMessage message = null;
        try {
            if (uHelper.getUserByUsername(user.getUsername()) != null)
                throw new Exception("Uzivatel uz existuje");

            uHelper.addNewUser(user);
            message = new FacesMessage(FacesMessage.SEVERITY_INFO,
                    "Uzivatel uspesne vytvoreny.",
                    "Uzivatel uspesne vytvoreny.");
            FacesContext.getCurrentInstance().addMessage(null, message);

            log.info("Uzivatel " + user.getUsername() + " uspesne vytvoreny.");
        } catch (Exception ex) {
            message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    ex.getMessage(), ex.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, message);
        }
    }

}
