package online.filter.develop;

import java.io.IOException;
import java.security.PrivilegedAction;
import java.util.Objects;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * HotDeployフィルタ
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
public class S2HotDeployFilter implements Filter, S2HotDeploy {

    /** 対象パッケージ */
    private String[] inc;
    /** 対象外パッケージ */
    private String[] exc;

    /**
     * @see javax.servlet.Filter#destroy()
     */
    @Override
    public void destroy() {
        return;
    }

    /**
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    @Override
    public void init(final FilterConfig filterConfig) {
        String val = filterConfig.getInitParameter("include");
        if (!Objects.toString(val, "").isEmpty()) {
            this.inc = val.split(",");
        }
        val = filterConfig.getInitParameter("exclude");
        if (!Objects.toString(val, "").isEmpty()) {
            this.exc = val.split(",");
        }
    }

    /**
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
     * javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response,
            final FilterChain chain) throws IOException, ServletException {
        doChain(request, response, chain,
            cl -> {
                Thread.currentThread().setContextClassLoader(cl);
                chain.doFilter(request, response);
            }
        );
    }

    /**
     * @see online.filter.develop.S2HotDeploy#getClassLoaderSupplier(java.lang.ClassLoader)
     */
    @Override
    public PrivilegedAction<ClassLoader> getClassLoaderSupplier(final ClassLoader org) {
        return () -> new S2HotDeployClassLoader(org, this.inc, this.exc);
    }
}
