package ru.micord.ervu.security.webbpm.jwt.util;

import java.util.Optional;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.util.WebUtils;
import ru.micord.ervu.security.webbpm.jwt.JwtAuthentication;
import ru.micord.ervu.security.webbpm.jwt.UserIdsPair;


import static ru.micord.ervu.security.SecurityConstants.AUTH_TOKEN;
public final class SecurityUtil {

  private SecurityUtil() {
    //empty
  }

  public static String extractAuthToken(HttpServletRequest httpRequest) {
    Cookie cookie = WebUtils.getCookie(httpRequest, AUTH_TOKEN);
    return cookie != null ? cookie.getValue() : null;
  }

  public static String getCurrentUsername() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null && auth.isAuthenticated()) {
      return auth.getName();
    }
    return null;
  }

  public static String getUserAccountId() {
    return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
        .map(a -> ((JwtAuthentication) a).getUserAccountId())
        .orElse(null);
  }
  
  public static UserIdsPair getUserIdsPair() {
    return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
        .map(a -> ((JwtAuthentication) a).getUserIdsPair())
        .orElse(null);
  }
}
