/* BdfServer - Copyright (c) 2014-2023 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.xml.subsettree;

import fr.exemole.bdfserver.api.subsettree.GroupNode;
import fr.exemole.bdfserver.api.subsettree.SubsetNode;
import fr.exemole.bdfserver.api.subsettree.SubsetTree;
import java.io.IOException;
import net.mapeadores.util.xml.XMLPart;
import net.mapeadores.util.xml.XMLWriter;


/**
 *
 * @author Vincent Calame
 */
public class TreeXMLPart extends XMLPart {

    public TreeXMLPart(XMLWriter xmlWriter) {
        super(xmlWriter);
    }

    public void addTree(SubsetTree subsetTree) throws IOException {
        openTag("tree");
        for (SubsetTree.Node node : subsetTree.getNodeList()) {
            if (node instanceof SubsetNode) {
                addSubsetNode((SubsetNode) node);
            } else if (node instanceof GroupNode) {
                addGroupNode((GroupNode) node);
            }
        }
        closeTag("tree");
    }

    private void addGroupNode(GroupNode groupNode) throws IOException {
        startOpenTag("group");
        addAttribute("name", groupNode.getName());
        endOpenTag();
        for (SubsetTree.Node subnode : groupNode.getSubnodeList()) {
            if (subnode instanceof SubsetNode) {
                addSubsetNode((SubsetNode) subnode);
            } else if (subnode instanceof GroupNode) {
                addGroupNode((GroupNode) subnode);
            }
        }
        closeTag("group");
    }

    private void addSubsetNode(SubsetNode subsetNode) throws IOException {
        addSimpleElement("subset", subsetNode.getSubsetKey().getKeyString());
    }

}
