package it.mice.voila.runtime.web.filter;

import java.util.Iterator;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

public class RuntimeMultipartResolver extends CommonsMultipartResolver {

	/**
	 * Set whether to resolve the multipart request lazily at the time of file
	 * or parameter access.
	 * <p>
	 * Default is "false", resolving the multipart elements immediately,
	 * throwing corresponding exceptions at the time of the
	 * {@link #resolveMultipart} call. Switch this to "true" for lazy multipart
	 * parsing, throwing parse exceptions once the application attempts to
	 * obtain multipart files or parameters.
	 */
	public void setResolveLazily(boolean resolveLazily) {
		if (resolveLazily) {
			throw new IllegalArgumentException(
					"Cannot use resolveLazily for this type of Multipart Request");
		}
	}

	@Override
	public MultipartHttpServletRequest resolveMultipart(
			HttpServletRequest request) throws MultipartException {

		ServletRequest appoRequest = request;
		while (appoRequest instanceof HttpServletRequestWrapper) {
			if (appoRequest instanceof MultipartHttpServletRequest) {
				return (MultipartHttpServletRequest)appoRequest;
			}
			appoRequest = ((HttpServletRequestWrapper)appoRequest).getRequest(); 
		}
		return super.resolveMultipart(request);
	}

	public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request, String submitButtonPrefix) throws MultipartException {
		Assert.notNull(request, "Request must not be null");
		MultipartParsingResult parsingResult = parseRequest(request);
		
		Iterator<String> i = parsingResult.getMultipartParameters().keySet().iterator();
		while (i.hasNext()) {
			String parmName = (String) i.next();
            if (parmName.startsWith(submitButtonPrefix)) {
                int endIndex = parmName.indexOf("?");
                String methodName;
                String queryString = null;
                if (endIndex == -1) {
                    methodName = parmName.substring(submitButtonPrefix.length());
                } else {
                    methodName = parmName.substring(submitButtonPrefix.length(), endIndex);
                    queryString = parmName.substring(endIndex + 1);
                    parsingResult.getMultipartParameters().putAll(RequestUtils.convertToParameterMap(queryString));
                }
        		return new RuntimeMultipartHttpServletRequest(request,
        				parsingResult.getMultipartFiles(),
        				parsingResult.getMultipartParameters(), methodName, queryString);
            }

		}
		
		return new RuntimeMultipartHttpServletRequest(request,
				parsingResult.getMultipartFiles(),
				parsingResult.getMultipartParameters(), null, null);
	}

}
