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

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

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.support.StandardMultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;

public class RuntimeMultipartResolver extends StandardServletMultipartResolver {

	/**
	 * 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");
		}
	}

	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");
		StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = new StandardMultipartHttpServletRequest(request);
		Map<String, String[]> parametersMap = standardMultipartHttpServletRequest.getParameterMap();
		Iterator<String> i = parametersMap.keySet().iterator();
		while (i.hasNext()) {
			String parmName = (String) i.next();
			String[] value = parametersMap.get(parmName);
            if (parmName.startsWith(submitButtonPrefix)) {
                int endIndex = parmName.indexOf("?");
                String methodName;
                String queryString = null;
                Map<String, String[]> newParametersMap = new HashMap<String, String[]>();
                if (endIndex == -1) {
                    methodName = parmName.substring(submitButtonPrefix.length());
                } else {
                    methodName = parmName.substring(submitButtonPrefix.length(), endIndex);
                    queryString = parmName.substring(endIndex + 1);                    
                    newParametersMap = RequestUtils.convertToParameterMap(queryString);
                }
        		return new RuntimeMultipartHttpServletRequest(request,
        				standardMultipartHttpServletRequest.getMultiFileMap(),
        				newParametersMap, methodName, queryString);
            }
            
		}
		
		return new RuntimeMultipartHttpServletRequest(request,
				standardMultipartHttpServletRequest.getMultiFileMap(),
				new HashMap<String, String[]>(), null, null);
	}

}
