package Tools;

import java.util.*;

/**
 * A data structure kind of like a Map, except that the get() operation
 * returns the stored value associated with the longest key that's a
 * prefix of the argument key.<p>
 *
 * I use it to look up information bound to a URL or any prefix of it
 * in {@link jp.SfUserAgent}.
 */
// We'll start with a grotesquely naive implementation.
// TODO: do something remotely intelligent.
public class PrefixMap {
	Map keymap;

	public PrefixMap() {
		keymap = new HashMap();
	}

	public void put(String key, Object value) {
		keymap.put(key, value);
	}

	public Object get(String key) {
		// System.out.println("Looking for key "+key);
		int lengthLongestPrefix = -1;
		Object correspondingValue = null;

		Iterator iter = keymap.keySet().iterator();
		while (iter.hasNext()) {
			String candidateKey = (String) iter.next();
			if (key.startsWith(candidateKey)) {
				if (candidateKey.length() > lengthLongestPrefix) {
					lengthLongestPrefix = candidateKey.length();
					correspondingValue = keymap.get(candidateKey);
					// System.out.println("found match at "+candidateKey);
				}
			}
		}
		return correspondingValue;
	}
}
