/*
 * $Id: HTMLNodeMapImpl.java 220 2007-07-16 10:32:15Z sugimotokenichi $
 * Copyright (C) 2005 SUGIMOTO Ken-ichi
 * 作成日： 2005/07/29
 */
package feat2.template.impl;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

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

import feat2.template.HTMLNode;
import feat2.template.HTMLNodeMap;


/**
 * 一意の名前がついているノードのマップ。
 * @author SUGIMOTO
 */
public class HTMLNodeMapImpl implements HTMLNodeMap, NamedNodeMap {

    private Map map;

    public HTMLNodeMapImpl() {
        map = new HashMap();
    }

    public void put(String name, HTMLNode node) {
        map.put(name, node);
    }

    public int size() {
        return map.size();
    }

    public HTMLNode get(String name) {
        return (HTMLNode)map.get(name);
    }

    public String[] getNames() {
        String[] ret = new String[map.size()];
        int i = 0;
        for(Iterator it = map.keySet().iterator(); it.hasNext(); ) {
            ret[i++] = (String)it.next();
        }
        return ret;
    }

    /**
     * このマップの値の反復子を返す。
     * @return
     */
    public Iterator iterator() {
        return Collections.unmodifiableCollection(map.values()).iterator();
    }

    // NamedNodeMapの実装 -------------------------------------------------------

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

    public Node getNamedItem(String name) {
        return TemplateUtil.toDomNode(get(name));
    }

    public Node getNamedItemNS(String namespaceURI, String localName) {
        if ( namespaceURI == null )
            return getNamedItem(localName);
        else
            return null;
    }

    public Node item(int index) {
        String[] names = getNames();
        if ( 0 <= index && index < names.length ) {
            return TemplateUtil.toDomNode(get(names[index]));
        }
        else {
            return null;
        }
    }

    public Node removeNamedItem(String name) throws DOMException {
        throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "");
    }

    public Node removeNamedItemNS(String namespaceURI, String localName)
            throws DOMException {
        throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "");
    }

    public Node setNamedItem(Node arg) throws DOMException {
        throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "");
    }

    public Node setNamedItemNS(Node arg) throws DOMException {
        throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "");
    }
}
