package ru.micord.ervu.security.esia.token;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Eduard Tihomirov
 */
public class TokensStore {
  private static final Map<String, ExpiringToken> accessTokensMap = new ConcurrentHashMap<>();
  private static final Map<String, ExpiringToken> refreshTokensMap = new ConcurrentHashMap<>();

  public static void addAccessToken(String prnOid, String token, long expiresIn) {
    if (token != null) {
      long expiryTime = System.currentTimeMillis() + 1000L * expiresIn;
      accessTokensMap.put(prnOid, new ExpiringToken(token, expiryTime));
    }
  }

  public static String getAccessToken(String prnOid) {
    return accessTokensMap.get(prnOid).getAccessToken();
  }

  public static void removeExpiredAccessToken() {
    for (String key : accessTokensMap.keySet()) {
      ExpiringToken token = accessTokensMap.get(key);
      if (token != null && token.isExpired()) {
        accessTokensMap.remove(key);
      }
    }
  }

  public static void removeExpiredRefreshToken() {
    for (String key : refreshTokensMap.keySet()) {
      ExpiringToken token = refreshTokensMap.get(key);
      if (token != null && token.isExpired()) {
        refreshTokensMap.remove(key);
      }
    }
  }

  public static void removeAccessToken(String prnOid) {
    accessTokensMap.remove(prnOid);
  }

  public static void addRefreshToken(String prnOid, String token, long expiresIn) {
    if (token != null) {
      long expiryTime = System.currentTimeMillis() + 1000L * expiresIn;
      refreshTokensMap.put(prnOid, new ExpiringToken(token, expiryTime));
    }
  }

  public static String getRefreshToken(String prnOid) {
    return refreshTokensMap.get(prnOid).getAccessToken();
  }

  public static void removeRefreshToken(String prnOid) {
    refreshTokensMap.remove(prnOid);
  }
}
