/* BdfServer - Copyright (c) 2019-2020 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.subsettree;

import fr.exemole.bdfserver.api.subsettree.GroupNode;
import fr.exemole.bdfserver.api.subsettree.SubsetNode;
import fr.exemole.bdfserver.api.subsettree.SubsetTree;
import java.util.ArrayList;
import java.util.List;


/**
 *
 * @author Vincent Calame
 */
public abstract class NodeListBuilder {

    private final List<Object> nodeList = new ArrayList<Object>();

    public NodeListBuilder() {

    }

    public void addSubsetNode(SubsetNode subsetNode) {
        nodeList.add(subsetNode);
    }

    public void addGroupNode(GroupNode groupNode) {
        nodeList.add(groupNode);
    }

    public void addGroupNodeBuilder(GroupNodeBuilder groupNodeBuilder) {
        nodeList.add(groupNodeBuilder);
    }

    protected List<SubsetTree.Node> toNodeList(boolean ignoreEmptyGroupNode) {
        int size = nodeList.size();
        SubsetTree.Node[] result = new SubsetTree.Node[size];
        int p = 0;
        for (Object obj : nodeList) {
            if (obj instanceof SubsetNode) {
                result[p] = (SubsetNode) obj;
                p++;
            } else if (obj instanceof GroupNode) {
                GroupNode groupNode = (GroupNode) obj;
                if ((ignoreEmptyGroupNode) && (groupNode.getSubnodeList().isEmpty())) {
                    continue;
                } else {
                    result[p] = groupNode;
                    p++;
                }
            } else if (obj instanceof GroupNodeBuilder) {
                GroupNode groupNode = ((GroupNodeBuilder) obj).toGroupNode();
                if ((ignoreEmptyGroupNode) && (groupNode.getSubnodeList().isEmpty())) {
                    continue;
                } else {
                    result[p] = groupNode;
                    p++;
                }
            }
        }
        if (p < size) {
            SubsetTree.Node[] tmp = new SubsetTree.Node[p];
            System.arraycopy(result, 0, tmp, 0, p);
            result = tmp;
        }
        return TreeUtils.wrap(result);
    }

}
