package inc.monsters.mias;

import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;

public class LoginBean {
	private String userName;
	private String password;

	/* This map will be filled by the FacesServlet, via a managed property */
	private Map<String, String> logins;

	public void setLogins(Map<String, String> logins) {
		this.logins = logins;
	}

	public synchronized Map<String, String> getLogins() {
		return logins;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void validateUserName(FacesContext context,
			                     UIComponent toValidate,
			                     Object value) {
		if (value == null || "".equals(value) || getLogins().get(value) == null) {
			((UIInput) toValidate).setValid(false);
			FacesMessage message = new FacesMessage("Invalid user name.");
			context.addMessage(toValidate.getClientId(context), message);
		}
	}

	public String login() {
		if (getUserName() != null 
				&& getLogins().get(getUserName()) != null
				&& getLogins().get(getUserName()).equals(getPassword())) {
			return "login";
		} else {
			return "error";
		}
	}
}
