package com.moex.asts.export;

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

import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XmlUtil {

    public static void loadStringMap(NodeList list, Map<String, String> hash, String keyName, String valueName) {
        for (int i = 0; i < list.getLength(); i++) {
            NamedNodeMap attributes = list.item(i).getAttributes();
            Node name = attributes.getNamedItem(keyName);
            if (name != null) {
                Node value = attributes.getNamedItem(valueName);
                String text = value == null ? null : value.getTextContent();
                hash.put(name.getTextContent(), text);
            }
        }
    }

    public static void loadStringMap(NodeList list, Map<String, String> hash, String keyName) {
        loadStringMap(list, hash, keyName, "value");
    }

    public static void loadStringMap(NodeList list, Map<String, String> hash) {
        loadStringMap(list, hash, "name", "value");
    }

    public static Map<String, String> loadStringMap(NodeList list) {
        Map<String, String> hash = new HashMap<>();
        loadStringMap(list, hash);
        return hash;
    }

    public static Element getFirstChild(Element root, String name) throws SAXException {
        NodeList list = root.getElementsByTagName(name);
        if (list == null)
            return null;
        if (list.getLength() > 1)
            throw new SAXException("Element " + root.getTagName() +
                    " has " + list.getLength() + " children " + name);
        return (Element) list.item(0);
    }

    public static Element getSingleChild(Element root, String name) throws SAXException {
        Element node = getFirstChild(root, name);
        if (node == null)
            throw new SAXException("Element " + root.getTagName() +
                    " has no child " + name);
        return node;
    }

    private XmlUtil() {
    }

}
