/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.exts.struts2.servlet;

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

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

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.servlet.ServletHostConfig;

/**
 */
@SuppressWarnings("serial")
public class NutsStrutsServlet extends HttpServlet {
	private NutsPrepareOperations prepare;
	private NutsExecuteOperations execute;
	private List<Pattern> excludedPatterns = null;

	@Override
	public void init(ServletConfig servletConfig) throws ServletException {
		InitOperations init = new InitOperations();
		try {
			ServletHostConfig config = new ServletHostConfig(servletConfig);
			init.initLogging(config);
			Dispatcher dispatcher = init.initDispatcher(config);
			init.initStaticContentLoader(config, dispatcher);

			prepare = new NutsPrepareOperations(servletConfig.getServletContext(), dispatcher);
    		execute = new NutsExecuteOperations(servletConfig.getServletContext(), dispatcher);

    		excludedPatterns = init.buildExcludedPatternsList(dispatcher);
		}
		finally {
			init.cleanup();
		}
	}

	@Override
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		try {
			prepare.setEncodingAndLocale(request, response);
			prepare.createActionContext(request, response);
			prepare.assignDispatcherToThread();
			if (excludedPatterns != null
					&& prepare.isUrlExcluded(request, excludedPatterns)) {
				return;
			}

			request = prepare.wrapRequest(request);
	        ActionMapping mapping = prepare.findActionMapping(request, response);

	        if (mapping == null) {
	            boolean handled = execute.executeStaticResourceRequest(request, response);
	            if (!handled) {
					throw new ServletException(
						"Resource loading not supported, use the StrutsPrepareAndExecuteFilter instead.");
	            }
	        }
	        else {
	            execute.executeAction(request, response, mapping);
	        }
		}
		finally {
			prepare.cleanupRequest(request);
		}
	}

	@Override
	public void destroy() {
		prepare.cleanupDispatcher();
	}
}
