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

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.util.WebUtils;
import ru.micord.ervu.security.webbpm.jwt.JwtAuthentication;

import static org.springframework.web.context.request.RequestAttributes.REFERENCE_REQUEST;

public final class SecurityUtil {
  public static final String AUTH_TOKEN = "auth_token";

  public static final String AUTH_MARKER = "webbpm.ervu-lkrp-fl";

  private SecurityUtil() {
    //empty
  }

  public static Cookie createCookie(String name, String value, String path) {
    String cookieValue = value != null ? URLEncoder.encode(value, StandardCharsets.UTF_8) : null;
    Cookie cookie = new Cookie(name, cookieValue);
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(
        REFERENCE_REQUEST);

    if (path != null) {
      cookie.setPath(path);
    }
    else {
      cookie.setPath(request.getContextPath());
    }
    cookie.setHttpOnly(true);

    return cookie;
  }

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

  public static String getErvuId() {
    return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
        .map(a -> ((JwtAuthentication) a).getUserAccountId())
        .map(userAccountId -> {
          String ervuId = userAccountId.split(":")[1];
          return "null".equals(ervuId) ? null : ervuId;
        })
        .orElse(null);
  }
}
