package ru.micord.ervu.security;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import ru.micord.ervu.security.esia.service.EsiaAuthService;

public class LogoutSuccessHandler
    implements org.springframework.security.web.authentication.logout.LogoutSuccessHandler {

  private final CsrfTokenRepository csrfTokenRepository;
  private final EsiaAuthService esiaAuthService;

  public LogoutSuccessHandler(CsrfTokenRepository csrfTokenRepository,
                              EsiaAuthService esiaAuthService) {
    this.csrfTokenRepository = csrfTokenRepository;
    this.esiaAuthService = esiaAuthService;
  }

  @Override
  public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                              Authentication authentication) throws IOException {
    String url = esiaAuthService.logout(request, response);
    response.sendRedirect(url);
    CsrfToken csrfToken = this.csrfTokenRepository.generateToken(request);
    this.csrfTokenRepository.saveToken(csrfToken, request, response);
  }
}
