package hirondelle.web4j;

import hirondelle.web4j.model.AppException;
import hirondelle.web4j.security.LoginTasks;
import hirondelle.web4j.util.Util;

import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

final class LoginTasksHelper {

  void reactToNewLogins(HttpServletRequest aRequest) throws AppException {
    HttpSession session = aRequest.getSession(DO_NOT_CREATE);
    if ( sessionExists(session) ){
      if( userHasLoggedIn(aRequest) ){
        LoginTasks loginTasks = BuildImpl.forLoginTasks();
        if(! loginTasks.hasAlreadyReacted(session)){
          fLogger.fine("New login detected.");
          loginTasks.reactToUserLogin(session, aRequest);          
        }
      }
    }
  }
  
  // PRIVATE 
  
  private static final boolean DO_NOT_CREATE = false;
  private static final Logger fLogger = Util.getLogger(Controller.class);
  
  private boolean sessionExists(HttpSession aSession){
    return aSession != null;
  }
  
  private boolean userHasLoggedIn(HttpServletRequest aRequest){
    return aRequest.getUserPrincipal() != null;
  }
}
