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

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import ru.micord.ervu.security.webbpm.jwt.util.SecurityUtil;

import static ru.micord.ervu.security.webbpm.jwt.util.SecurityUtil.AUTH_MARKER;
import static ru.micord.ervu.security.webbpm.jwt.util.SecurityUtil.AUTH_TOKEN;
import static ru.micord.ervu.security.webbpm.jwt.util.SecurityUtil.createCookie;

public final class SecurityHelper {
  @Value("${cookie.path:#{null}}")
  private String accessCookiePath;

  public void clearAccessCookies(HttpServletResponse response) {
    Cookie tokenCookie = createCookie(AUTH_TOKEN, null, null);
    tokenCookie.setMaxAge(0);
    tokenCookie.setPath(accessCookiePath);
    tokenCookie.setHttpOnly(true);
    response.addCookie(tokenCookie);

    Cookie markerCookie = createCookie(AUTH_MARKER, null, null);
    markerCookie.setMaxAge(0);
    markerCookie.setPath("/");
    response.addCookie(markerCookie);
  }

  public Cookie createAccessCookie(String cookieValue, int expiry) {
    Cookie authToken = createCookie(SecurityUtil.AUTH_TOKEN, cookieValue, accessCookiePath);
    authToken.setPath(accessCookiePath);
    authToken.setMaxAge(expiry);
    return authToken;
  }

  public Cookie createAuthMarkerCookie(String cookieValue, int expiry) {
    Cookie marker = createCookie(AUTH_MARKER, cookieValue, "/");
    marker.setMaxAge(expiry);
    marker.setHttpOnly(false);
    return marker;
  }
}
