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

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;

public class RequestUtils {

    public static Map convertToParameterMap(String queryString) {
        HashMap map = new HashMap();
        StringTokenizer st = new StringTokenizer(queryString, "&");
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            StringTokenizer st2 = new StringTokenizer(token, "=");
            String paramName = st2.nextToken();
            String paramValue = null;
            if (st2.hasMoreTokens()) {
            	paramValue = st2.nextToken();
            }
            if (map.get(paramName) == null) {
                map.put(paramName, new String[] {paramValue});
            } else {
                String[] currentValues = (String[])map.get(paramName);
                String[] newValues = new String[currentValues.length + 1];
                System.arraycopy(currentValues, 0, newValues, 0, currentValues.length);
                newValues[currentValues.length] = paramValue;
                map.put(paramName, newValues);
            }
        }
        return map;
    }

    public static String findSubmitButtonParameterName(HttpServletRequest request, String buttonSubmitPrefix) throws IOException {
        Enumeration e = request.getParameterNames();
        while (e.hasMoreElements()) {
            String parmName = (String) e.nextElement();
            if (parmName.startsWith(buttonSubmitPrefix)) {
                return parmName;
            }
        }
//        if (ServletFileUpload.isMultipartContent((HttpServletRequest)request)) {
//            ServletFileUpload upload = new ServletFileUpload();
//            FileItemIterator iter = upload.getItemIterator(request);
//            while (iter.hasNext()) {
//            	FileItemStream item = iter.next();
//            	String parmName = item.getFieldName();
//                if (parmName.startsWith(BUTTON_SUBMIT_PREFIX)) {
//                    return parmName;
//                }
//            }
//        }
        return null;
    }

}
