package email;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

public abstract class SecureEmailApp {

  private Map<String, LocalDateTime> loggedInUsers = new HashMap<>();

  public void openInbox(String userId) {
    if (isAlreadyAuthenticated(userId)) {
      System.out.println("Opening inbox for " + userId);
    } else {
      askToLoginAndThen(userId, (id) -> openInbox(userId), 2);
    }
  }

  private void askToLoginAndThen(String userId, Consumer<String> action, int attemptsRemaining) {
    if (checkIdentity(userId)) {
      loggedInUsers.put(userId, LocalDateTime.now());
      action.accept(userId);
    } else {
      if (attemptsRemaining > 0) {
        askToLoginAndThen(userId, action, attemptsRemaining - 1);
      } else {
        System.out.println("Authentication failed.");
      }
    }
  }

  protected abstract boolean checkIdentity(String userId);

  private boolean isAlreadyAuthenticated(String userId) {
    return loggedInUsers.containsKey(userId)
        && loggedInUsers.get(userId).isAfter(LocalDateTime.now().minusHours(6));
  }
}

