package org.richfaces.realworld.manager;

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

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.End;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.richfaces.realworld.domain.User;
import org.richfaces.realworld.service.Constants;
import org.richfaces.realworld.service.FlushStrategy;
import org.richfaces.realworld.service.IUserAction;
import org.richfaces.realworld.ui.PasswordHolder;

@Name("registerManager")
@Scope(ScopeType.CONVERSATION)
public class RegistrationManager {
	
	@In("#{messages['user.exist']}") private String USER_WITH_THIS_LOGIN_ALREADY_EXIST;

	@In("#{messages['user.confirm.error']}") private String CONFIRM_PASSWORD_NOT_EQUALS_PASSWORD;

	@Logger Log log;
	
    @In Identity identity;
    
    @In Credentials credentials;
	
    @In FacesMessages facesMessages;
    
	@In PasswordHolder passwordHolder;
	@In IUserAction userAction;
    
	@End
    public String register(User user){
    	if(checkPassword(user) || checkUserExist(user)){
    		return "";
    	}
    	user.setPasswordHash(passwordHolder.hash(user.getPassword()));
    	userAction.register(user);
    	return "index";
    }
	
	public String goToRegister(){
    	identity.logout();
    	identity.unAuthenticate();
    	credentials.clear();
    	credentials.invalidate();
    	return "register";
    }
	
	private boolean checkUserExist(User user) {
		if(userAction.isUserExist(user.getLogin())){
    		UIComponent root = FacesContext.getCurrentInstance().getViewRoot();
    		UIComponent component = root.findComponent(Constants.REGISTER_LOGIN_NAME_ID);
			FacesContext.getCurrentInstance().addMessage(component.getClientId(FacesContext.getCurrentInstance()), new FacesMessage(
					FacesMessage.SEVERITY_ERROR, USER_WITH_THIS_LOGIN_ALREADY_EXIST , USER_WITH_THIS_LOGIN_ALREADY_EXIST));
			return true;
    	}
		return false;
	}

	private boolean checkPassword(User user) {
		if(!user.getPassword().equals(user.getConfirmPassword())){
    		UIComponent root = FacesContext.getCurrentInstance().getViewRoot();
    		UIComponent component = root.findComponent(Constants.REGISTER_CONFIRM_PASSWORD_ID);
			FacesContext.getCurrentInstance().addMessage(component.getClientId(FacesContext.getCurrentInstance()), new FacesMessage(
					FacesMessage.SEVERITY_ERROR, CONFIRM_PASSWORD_NOT_EQUALS_PASSWORD , CONFIRM_PASSWORD_NOT_EQUALS_PASSWORD));
			return true;
    	}
		return false;
	}
}
