package nuts.exts.struts2.test;


import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nuts.exts.struts2.operations.NutsExecuteOperations;
import nuts.exts.struts2.operations.NutsPrepareOperations;

import org.apache.struts2.StrutsConstants;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.apache.struts2.dispatcher.ng.InitOperations;
import org.apache.struts2.dispatcher.ng.filter.FilterHostConfig;

import com.opensymphony.xwork2.inject.Inject;

/**
 * Struts Test Filter.
 */
public class StrutsTestFilter implements StrutsStatics, Filter {
    protected NutsPrepareOperations prepare;
    protected NutsExecuteOperations execute;
	protected List<Pattern> excludedPatterns = null;

	protected Dispatcher dispatcher;
	protected String actionExtension = "action";
	
    /**
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    public void init(FilterConfig filterConfig) throws ServletException {
        InitOperations init = new InitOperations();
        try {
            FilterHostConfig config = new FilterHostConfig(filterConfig);
            init.initLogging(config);
            dispatcher = init.initDispatcher(config);
            init.initStaticContentLoader(config, dispatcher);

            prepare = new NutsPrepareOperations(filterConfig.getServletContext(), dispatcher);
            execute = new NutsExecuteOperations(filterConfig.getServletContext(), dispatcher);
			this.excludedPatterns = init.buildExcludedPatternsList(dispatcher);

            postInit(dispatcher, filterConfig);
        } finally {
            init.cleanup();
        }

    }

    /**
     * Callback for post initialization
     */
    protected void postInit(Dispatcher dispatcher, FilterConfig filterConfig) {
		dispatcher.getContainer().inject(this);
    }

    /**
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        try {
            prepare.setEncodingAndLocale(request, response);
            prepare.createActionContext(request, response);
            prepare.assignDispatcherToThread();
			if ( excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {
				chain.doFilter(request, response);
			} else {
				request = prepare.wrapRequest(request);
				ActionMapping mapping = prepare.findActionMapping(request, response, true);
				if (mapping == null) {
					boolean handled = execute.executeStaticResourceRequest(request, response);
					if (!handled) {
						chain.doFilter(request, response);
					}
				} else {
					execute.executeAction(request, response, mapping);
				}
			}
        } finally {
            //prepare.cleanupRequest(request);
        }
    }

    /**
	 * @return the dispatcher
	 */
	public Dispatcher getDispatcher() {
		return dispatcher;
	}

	/**
	 * @return the actionExtension
	 */
	public String getActionExtension() {
		return actionExtension;
	}

	/**
	 * @param actionExtension the actionExtension to set
	 */
    @Inject(StrutsConstants.STRUTS_ACTION_EXTENSION)
	public void setActionExtension(String actionExtension) {
		this.actionExtension = actionExtension;
	}

	/**
     * @param request request
     */
    public void cleanUp(HttpServletRequest request) {
        prepare.cleanupRequest(request);
    }

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