package com.atlassian.stash.internal.hazelcast;

import com.hazelcast.web.WebFilter;

import javax.servlet.*;
import java.io.IOException;

/**
 * Wrapper around the Hazelcast {@code WebFilter} that manages distribution of session data across the cluster. The
 * wrapper allows enabling/disabling of the session distribution across the cluster by optionally bypassing the
 * Hazelcast filter.
 */
public class ConfigurableWebFilter implements Filter {

    private final WebFilter delegate;
    private final boolean enabled;

    public ConfigurableWebFilter(HazelcastSessionMode config, WebFilter delegate) {
        this.enabled = config != HazelcastSessionMode.LOCAL;
        this.delegate = delegate;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        if (enabled) {
            delegate.init(filterConfig);
        } else {
            // no need to fully initialize the WebFilter, but we do need to register it so SessionListener can find it
            filterConfig.getServletContext().setAttribute(WebFilter.class.getName(), delegate);
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (enabled) {
            delegate.doFilter(request, response, chain);
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        if (enabled) {
            delegate.destroy();
        }
    }
}
