package gov.va.med.edp.springframework.security.ui.vistalink;

import org.springframework.security.ui.logout.LogoutHandler;
import org.springframework.security.Authentication;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import gov.va.med.edp.springframework.security.userdetails.VistaUserDetailsService;
import gov.va.med.edp.springframework.security.providers.vistalink.VistaAuthenticationToken;

public class VistaLogoutHandler implements LogoutHandler, InitializingBean {

    private VistaUserDetailsService userDetailsService;

    public void afterPropertiesSet() throws Exception {
        Assert.notNull(userDetailsService, "userDetailsService must be set.");
    }

    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        if (!(authentication instanceof VistaAuthenticationToken)) return;
        VistaAuthenticationToken auth = (VistaAuthenticationToken) authentication;
        userDetailsService.logout(auth.getVistaUserDetails());
    }

    public VistaUserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(VistaUserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
