package dendrarium.portal.admin;

import dendrarium.core.entities.User;
import java.io.Serializable;
import static org.jboss.seam.ScopeType.EVENT;
import java.util.List;
import org.hibernate.Session;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.RaiseEvent;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.faces.FacesMessages;

@Scope(EVENT)
@Name("register")
public class Register implements Serializable {

    @In(required = false)
    @Out(required = false)
    private User newUser;

    @In
    Session session;

    @In
    private FacesMessages facesMessages;

    private String verify = "";

    private boolean registered;

    @Factory(value = "newUser")
    public User newUser() {
        return new User("", "", "");
    }

    @RaiseEvent("userListChange")
    public void register() {
        if (newUser.getPassword().equals(verify)) {
            List existing = session.createQuery("select u.username from User u where u.username=#{newUser.username}").list();
            if (existing.size() == 0) {
                session.persist(newUser);
                facesMessages.add("Zarejestrowałeś użytkownika #{newUser.username}");
                registered = true;
                isRegistered();
            } else {
                facesMessages.addToControl("username", "Użytkownik #{newUser.username} już istnieje");
            }
        } else {
            facesMessages.addToControl("verify", "Wprowadź ponownie hasło");
            verify = null;
        }
    }

    public void invalid() {
        facesMessages.add("Spróbuj ponownie");
    }

    public boolean isRegistered() {
        return registered;
    }

    public String getVerify() {
        return verify;
    }

    public void setVerify(String verify) {
        this.verify = verify;
    }
}
