package mildo.wiwo.user;

import mildo.wiwo.data.WiwoUser;

import com.webobjects.eocontrol.EOEditingContext;
import com.webobjects.foundation.NSTimestamp;

public class UserManager 
	implements UserRoleDefs
{

	public UserManager(EOEditingContext aCtx) {
		editingContext = aCtx;
	}
	
	private EOEditingContext editingContext;
	
	/**
	 * Creates user
	 * @param aLogin
	 * @param aPwd
	 * @param aUserRole
	 * @return
	 */
	public WiwoUser createUser(String aLogin, String aPwd, String aUserRole) {
		return WiwoUser.createWiwoUser(editingContext, aLogin, aPwd, aUserRole);
	}
	
	/**
	 * Processes login of customer into session
	 * @return UserLoginResult object or null if some low-level (db for example) error
	 */
	public UserLoginResult processUserLogin(SessionWithUser aSession, String login, String pwd) {
		UserLoginResult result = fetchUserForLogin(login, pwd);
		if (result != null && result.getUser() != null && result.isLoginOk()) {
			aSession.setActualSessionUser(result.getUser());
		} else {
		}
		return result;
	}
	
	/**
	 * Loads GenericUser for login.
 	 * The userEmail alebo loginName is considered according useEmailAsLoginName.
	 * @return UserLoginResult object or null if some low-level (db for example) error
	 */
	public UserLoginResult fetchUserForLogin(String login, String pwd) {
		WiwoUser theUser = WiwoUser.fetchWiwoUser(editingContext, WiwoUser.LOGIN_KEY, login);
		if (theUser != null) {
			boolean theLoginCondition = false;
			theLoginCondition = (
				theUser.login() != null && theUser.password() != null &&
				theUser.login().equals(login) && theUser.password().equals(pwd));
			if (theLoginCondition) {
					// User is ok
					// aOk=true, aUnknown=false, aPwd=false
					return new UserLoginResult(theUser, true, false, false);
			} else {
				// User is ok, but pwd is wrong
				// aOk=false, aUnknown=false, aPwd=true
				return new UserLoginResult(theUser, false, false, true);
			}
		} else {
			// User is not known
			// aOk=false, aUnknown=true, aPwd=false
			return new UserLoginResult(null, false, true, false);
		}
	}
	
}
