/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 *
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.core.oxm.adapter;

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

import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

public class SimpleAttrMap implements NamedNodeMap {
	private Element element;
	private List<Node> nodeList;
	private Map<String, Integer> nodeMap;

	public SimpleAttrMap(Element element, List<Node> nodes) {
		this.element = element;
		this.nodeList = nodes;
		nodeMap = new HashMap<String, Integer>(nodes.size());
		for (int i = 0; i < nodes.size(); i++) {
			Node n = nodes.get(i);
			nodeMap.put(n.getNodeName(), i);
		}
	}

	public int getLength() {
		return nodeList.size();
	}

	public Node item(int index) {
		return nodeList.get(index);
	}

	public Node getNamedItem(String name) {
		Integer i = nodeMap.get(name);
		return i == null ? null : nodeList.get(i);
	}

	public Node removeNamedItem(String name) throws DOMException {
		Node node = getNamedItem(name);
		if (node != null) {
			element.removeAttribute(name);
		}
		return node;
	}

	public Node setNamedItem(Node node) throws DOMException {
		Attr a = (Attr)node;
		element.setAttribute(a.getName(), a.getValue());
		Integer i = nodeMap.get(a.getName());
		if (i == null) {
			nodeMap.put(a.getName(), nodeList.size());
			nodeList.add(a);
			return null;
		}
		else {
			Node old = nodeList.set(i, a);
			return old;
		}
	}

	public Node setNamedItemNS(Node node) throws DOMException {
		return setNamedItem(node);
	}

	public Node getNamedItemNS(String namespaceURI, String localName) {
		return getNamedItem(localName);
	}

	public Node removeNamedItemNS(String namespaceURI, String localName)
			throws DOMException {
		return removeNamedItem(localName);
	}
}
