/* BdfServer - Copyright (c) 2014-2022 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package fr.exemole.bdfserver.tools.memento.dom;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import net.mapeadores.util.xml.DOMUtils;
import org.w3c.dom.Element;


/**
 *
 * @author Vincent Calame
 */
public final class MementoTreeDOMReader {

    private MementoTreeDOMReader() {
    }

    public static Node readNode(Element element) {
        String name = element.getAttribute("name").trim();
        Node node = new Node(name);
        DOMUtils.readChildren(element, new NodeConsumer(node));
        return node;
    }


    public static class Node {

        private final String name;
        private final List<Node> subnodeList = new ArrayList<Node>();

        private Node(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public boolean isLeaf() {
            return subnodeList.isEmpty();
        }

        public List<Node> getSubnodeList() {
            return subnodeList;
        }

        private void add(Node node) {
            subnodeList.add(node);
        }

    }


    private static class NodeConsumer implements Consumer<Element> {

        private final Node parentNode;

        private NodeConsumer(Node parentNode) {
            this.parentNode = parentNode;
        }

        @Override
        public void accept(Element element) {
            String name = element.getAttribute("name").trim();
            if (name.length() == 0) {
                return;
            }
            String tagName = element.getTagName();
            if (tagName.equals("leaf")) {
                parentNode.add(new Node(name));
            } else if (tagName.equals("branch")) {
                Node subnode = new Node(name);
                NodeConsumer nodeHandler = new NodeConsumer(subnode);
                DOMUtils.readChildren(element, nodeHandler);
                parentNode.add(subnode);
            }
        }

    }

}
