package com.gwt.app.server;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.gwt.app.client.LoginService;
import com.gwt.app.shared.UserDTO;

public class LoginServiceImpl extends RemoteServiceServlet implements LoginService
{
    private static final long serialVersionUID = 4456105400553118785L;
 
    @Override
    public UserDTO loginServer(String name, String password)
    {
    	UserDTO user = new UserDTO(name, password);
    	user.setLoggedIn(true);
        storeUserInSession(user);
        return user;
    }
 
    @Override
    public UserDTO loginFromSessionServer()
    {
        return getUserAlreadyFromSession();
    }
 
    @Override
    public void logout()
    {
        deleteUserFromSession();
    }
 
    private UserDTO getUserAlreadyFromSession()
    {
        UserDTO user = null;
        HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
        HttpSession session = httpServletRequest.getSession();
        Object userObj = session.getAttribute("user");
        if (userObj != null && userObj instanceof UserDTO)
        {
            user = (UserDTO) userObj;
        }
        return user;
    }
 
    private void storeUserInSession(UserDTO user)
    {
        HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
        HttpSession session = httpServletRequest.getSession(true);
        user.setSessionId(session.getId());
        session.setAttribute("user", user);
    }
 
    private void deleteUserFromSession()
    {
        HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
        HttpSession session = httpServletRequest.getSession();
        session.removeAttribute("user");
    }
 
}