package org.seasar.jsf.runtime;

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

import org.seasar.framework.exception.EmptyRuntimeException;
import org.seasar.jsf.JsfConfig;
import org.seasar.jsf.TagConfig;
import org.seasar.jsf.TaglibConfig;
import org.seasar.jsf.TaglibManager;
import org.seasar.jsf.exception.PrefixNotFoundRuntimeException;
import org.seasar.jsf.exception.UriNotFoundRuntimeException;

/**
 * @author higa
 *
 */
public class JsfConfigImpl implements JsfConfig {

	private Map taglibUris = new HashMap();
	
	private Map prefixes = new HashMap();
	
	private TaglibManager taglibManager;
	
	public JsfConfigImpl() {
	}

	public void addTaglibUri(String prefix, String uri) {
		taglibUris.put(prefix, uri);
		prefixes.put(uri, prefix);

	}

	public boolean hasTaglibUri(String prefix) {
		return taglibUris.containsKey(prefix);
	}

	public String getTaglibUri(String prefix) {
		String uri = (String) taglibUris.get(prefix);
		if (uri != null) {
			return uri;
		}
		throw new PrefixNotFoundRuntimeException(prefix);
	}
	
	public String getTaglibPrefix(String uri) {
		String prefix = (String) prefixes.get(uri);
		if (prefix != null) {
			return prefix;
		}
		throw new UriNotFoundRuntimeException(uri);
	}

	public TagConfig getTagConfig(String prefix, String tagName) {
		String uri = getTaglibUri(prefix);
		TaglibConfig taglibConfig = getTaglibManager().getTaglibConfig(uri);
		return taglibConfig.getTagConfig(tagName);
	}

	public TagConfig getTagConfig(String inject) {
		int index = inject.indexOf(':');
		if (index < 0) {
			throw new IllegalArgumentException(inject);
		}
		String prefix = inject.substring(0, index);
		String tagName = inject.substring(index + 1);
		return getTagConfig(prefix, tagName);
	}

	public TaglibManager getTaglibManager() {
		if (taglibManager != null) {
			return taglibManager;
		}
		throw new EmptyRuntimeException("taglibManager");
	}

	public void setTaglibManager(TaglibManager taglibManager) {
		this.taglibManager = taglibManager;
	}
}
