/*
 * Enhydra Java Application Server Project
 * 
 * The contents of this file are subject to the Enhydra Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License on
 * the Enhydra web site (http://www.enhydra.org/).
 * 
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See 
 * the License for the specific terms governing rights and limitations
 * under the License.
 * 
 * The Initial Developer of the Enhydra Application Server is Lutris
 * Technologies, Inc. The Enhydra Application Server and portions created
 * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
 * All Rights Reserved.
 * 
 * Contributor(s):
 * 
 * $Id: ContextServices.java,v 1.2 2001/09/25 19:05:30 cryd0221 Exp $
 */
package org.enhydra.barracuda.core.util.http;

import java.util.*;

/**
 * <p>This class provides a simple series of static methods
 * to convert a Map to a URL String and vica-versa</p>
 */
public class HttpConverter {

	public static String cvtMapToURLString (Map map, String delimiter) {
		//eliminate the obvious
		if (map==null) return null;
	
		//run through the map and build a new string
		StringBuffer sb = new StringBuffer(200);
		String sep = "";
		Iterator it = map.keySet().iterator();
		while (it.hasNext()) {
			Object key = it.next();
			Object value = map.get(key);
			if (value instanceof Set) {
				Set set = (Set) value;
				Iterator it2 = set.iterator();
				while (it2.hasNext()) {
					sb.append(concat(sep, key, it2.next()));
				}							
			} else {
				sb.append(concat(sep, key, value));
			}
			sep = delimiter;
		}
		return sb.toString();
	}
	
	private static String concat(String sep, Object key, Object value) {
		return sep+key.toString()+"="+value.toString();
	}
	
	public static Map cvtURLStringToMap (String paramStr, String delimiter) {
		//build the HashMap
		HashMap map = new HashMap(10);
		int spos = 0;
		int epos = -1;
		int eqpos = -1;
		int max = paramStr.length();
		while (spos>=0 && spos<max) {
			eqpos = paramStr.indexOf("=",spos+1);
			if (eqpos<0) break;
			epos = paramStr.indexOf(delimiter,eqpos+1);
			if (epos<0 && eqpos>-1) epos = max;
			if (eqpos>spos || eqpos<epos) {
				String key = paramStr.substring (spos,eqpos);
				String value = paramStr.substring (eqpos+1, epos);
				if (map.containsKey(key)) {
					Object mapVal = map.get(key);
					if (mapVal instanceof Set) {
						((Set) mapVal).add(value);
					} else {
						Set set = new HashSet();
						map.put(key, set);					
						set.add(mapVal);
						set.add(value);
					}
				} else {
					map.put(key, value);
				}
			}
			spos = epos+1;
		}
		return map;
	}
}

