package de.duehl.swing.ui.tree;

/*
 * Copyright 2025 Christian Dühl. All rights reserved.
 *
 * This program is free software. You can redistribute it and/or
 * modify it under the same terms as perl:
 *
 * general:  http://dev.perl.org/licenses/
 * GPL:      http://dev.perl.org/licenses/gpl1.html
 * artistic: http://dev.perl.org/licenses/artistic.html
 */

import java.util.Collections;
import java.util.List;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

/**
 * Diese Klasse stellt einige Hilfsmethoden rund um JTrees zur Verfügung.
 *
 * Quelle: https://www.logicbig.com/tutorials/java-swing/jtree-expand-collapse-all-nodes.html
 *
 * @version 1.01     2025-07-20
 * @author Christian Dühl
 */

public class TreeHelper {

    /** Klappt alle Nodes aus. */
    public static void expandAll(JTree tree) {
        boolean expanded = true;
        setTreeExpandedState(tree, expanded);
    }

    /** Klappt alle Nodes ein. */
    public static void collapseAll(JTree tree) {
        boolean expanded = false;
        setTreeExpandedState(tree, expanded);
    }


    private static void setTreeExpandedState(JTree tree, boolean expanded) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getModel().getRoot();
        setNodeExpandedState(tree, node, expanded);
    }

    private static void setNodeExpandedState(JTree tree, DefaultMutableTreeNode node,
            boolean expanded) {
        List<TreeNode> list = Collections.list(node.children());
        for (TreeNode treeNode : list) {
            DefaultMutableTreeNode dmTreeNode = (DefaultMutableTreeNode) treeNode;
            setNodeExpandedState(tree, dmTreeNode, expanded);
        }
        if (!expanded && node.isRoot()) {
            return;
        }
        TreePath path = new TreePath(node.getPath());
        if (expanded) {
            tree.expandPath(path);
        }
        else {
            tree.collapsePath(path);
        }
    }
}
