package ru.ulstu.user.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.stereotype.Component;
import ru.ulstu.configuration.Constants;
import ru.ulstu.user.service.UserSessionService;

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

@Component
public class UserSessionLogoutHandler extends SimpleUrlLogoutSuccessHandler implements LogoutSuccessHandler {
    private final Logger log = LoggerFactory.getLogger(UserSessionLogoutHandler.class);
    private final UserSessionService userSessionService;

    public UserSessionLogoutHandler(UserSessionService userSessionService) {
        this.userSessionService = userSessionService;
        setDefaultTargetUrl(Constants.LOGOUT_URL);
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request,
                                HttpServletResponse response,
                                Authentication authentication) throws IOException, ServletException {
        if (authentication == null) {
            super.onLogoutSuccess(request, response, authentication);
            return;
        }
        final String login = authentication.getName();
        final String ipAddress = IpAddressResolver.getRemoteAddr(request);
        final String host = request.getRemoteHost();
        log.debug("Logout Success for {}@{} ({})", login, ipAddress, host);
        HttpSession session = request.getSession(false);
        if (session != null) {
            final String sessionId = session.getAttribute(Constants.SESSION_ID_ATTR).toString();
            userSessionService.closeUserSession(sessionId);
            session.removeAttribute(Constants.SESSION_ID_ATTR);
            session.invalidate();
        }
        super.onLogoutSuccess(request, response, authentication);
    }
}
