package de.thomasjacob.improve.presentation.login;

import de.thomasjacob.improve.logic.DaoLocator;
import de.thomasjacob.improve.logic.user.User;
import de.thomasjacob.webcore.TechnicalException;

import javax.servlet.http.HttpSession;


public class LoginManager
{
	public static final String UNAUTHORIZED_MESSAGE = "Not logged in or unauthorized to perform this operation.";

	private Integer userId = null;

	private LoginManager()
	{
	}

	public static synchronized LoginManager getInstance(HttpSession session)
	{
		LoginManager manager = (LoginManager) session.getAttribute(LoginManager.class.getName());
		if (manager == null)
		{
			manager = new LoginManager();
			session.setAttribute(LoginManager.class.getName(), manager);
		}

		return manager;
	}

	public User getUser() throws TechnicalException
	{
		if (userId == null)
		{
			return null;
		}

		return DaoLocator.getInstance().getUserDao().getUserById(userId.intValue());
	}

	public boolean isLoggedIn() throws TechnicalException
	{
		if (userId == null)
		{
			return false;
		}

		User user = getUser();
		return user.isEnabled();
	}

	public void login(User user)
	{
		this.userId = new Integer(user.getId());
	}

	public void logout()
	{
		userId = null;
	}
}