package gov.va.med.edp.web.controller;

import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.util.StringUtils;
import org.springframework.util.Assert;
import org.springframework.beans.factory.InitializingBean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;

/**
 * Controller for handling logout.
 * <p/>
 * Only logic for logout other than invalidating the session is remove the swfID from the list of recognized ones
 * for this session. If the count drops to 0, or the swfID is not supplied, then invalidate the session.
 */
public class LogoutController extends AbstractController implements InitializingBean {

    public static final String DEFAULT_VIEW_NAME = "logout";

    private String viewName = DEFAULT_VIEW_NAME;

    public void afterPropertiesSet() throws Exception {
        Assert.notNull(viewName, "viewName must not be null");
    }

    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String swfID = request.getParameter("swfID");
        if (!StringUtils.hasLength(swfID)) {
            request.getSession().invalidate();
        } else {
            String ids = (String) request.getSession().getAttribute(SessionConstants.RECOGNIZED_SWF_IDS_KEY);
            Set idSet = StringUtils.commaDelimitedListToSet(ids);
            if (idSet.isEmpty()) {
                request.getSession().invalidate();
            } else {
                idSet.remove(swfID);
                if (idSet.isEmpty()) {
                    request.getSession().setAttribute(SessionConstants.RECOGNIZED_SWF_IDS_KEY, null);
                    request.getSession().invalidate();
                } else {
                    ids = StringUtils.collectionToCommaDelimitedString(idSet);
                    request.getSession().setAttribute(SessionConstants.RECOGNIZED_SWF_IDS_KEY, ids);
                }
            }
        }

        return new ModelAndView(getViewName());
    }

    public String getViewName() {
        return viewName;
    }

    public void setViewName(String viewName) {
        this.viewName = viewName;
    }
}
