package net.sourceforge.ganttproject.gui;

import java.awt.Component;

import javax.swing.JComponent;
import javax.swing.JTree;
import javax.swing.tree.TreePath;

import org.jdesktop.swingx.JXTree;
import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode;
import org.jdesktop.swingx.treetable.DefaultTreeTableModel;

public abstract class UIUtil {
    public static void setEnabledTree(JComponent root, boolean isEnabled) {
        root.setEnabled(isEnabled);
        Component[] components = root.getComponents();
        for (int i = 0; i < components.length; i++) {
            if (components[i] instanceof JComponent) {
                setEnabledTree((JComponent) components[i], isEnabled);
            }
        }
    }

    public static void moveTreeNode(
            DefaultMutableTreeTableNode movedNode, DefaultMutableTreeTableNode targetNode, int position,
            JTree tree, DefaultTreeTableModel model) {
        TreePath movedPath = new TreePath(movedNode.getPath());
        boolean wasSelected = (tree.getSelectionModel().isPathSelected(movedPath));
        boolean wasExpanded = tree.isExpanded(movedPath);
        if (wasSelected) {
            tree.getSelectionModel().removeSelectionPath(movedPath);
        }
        model.removeNodeFromParent(movedNode);
        model.insertNodeInto(movedNode, targetNode,
                position<0 ? targetNode.getChildCount() : position);
        movedPath = new TreePath(movedNode.getPath());
        if (wasSelected) {
            tree.getSelectionModel().addSelectionPath(movedPath);
        }
        if (wasExpanded) {
            tree.expandPath(movedPath);
        }
    }
}
