import {math} from "@xeokit/xeokit-sdk/dist/xeokit-sdk.es.js";

const DEFAULT_DOUBLE_CLICK_THRESHOLD = 300;
const tempVec3 = math.vec3();

function collectObjectIdsInSubtree(treeViewPlugin, treeViewNode) {
    const objectIds = [];
    if (!treeViewPlugin || !treeViewNode) {
        return objectIds;
    }
    treeViewPlugin.withNodeTree(treeViewNode, (node) => {
        if (node.objectId) {
            objectIds.push(node.objectId);
        }
    });
    return objectIds;
}

function focusTreeNodeInViewer(bimViewer, treeViewPlugin, treeViewNode) {
    if (!bimViewer || !treeViewPlugin || !treeViewNode) {
        return;
    }

    const viewer = bimViewer.viewer;
    const scene = viewer.scene;
    const objectIds = collectObjectIdsInSubtree(treeViewPlugin, treeViewNode);

    if (objectIds.length === 0) {
        console.log("[treeViewFocusHelper] empty objectIds for node", treeViewNode);
        return;
    }

    const aabb = scene.getAABB(objectIds);
    if (!aabb || !Array.isArray(aabb) || aabb.length !== 6) {
        console.log("[treeViewFocusHelper] no AABB for objectIds", objectIds);
        return;
    }
    console.log("[treeViewFocusHelper] flyTo", {
        nodeId: treeViewNode.nodeId || treeViewNode.id,
        objectIds: objectIds.slice(0, 10),
        count: objectIds.length,
        aabb: aabb
    });

    // ensure visible/pickable before flying
    scene.setObjectsVisible(objectIds, true);
    scene.setObjectsPickable(objectIds, true);

    const center = math.getAABB3Center(aabb, tempVec3);
    viewer.cameraControl.pivotPos = center;

    viewer.cameraFlight.flyTo({
        aabb,
        duration: bimViewer.getConfig("viewFitDuration"),
        fitFOV: bimViewer.getConfig("viewFitFOV")
    }, () => {
        const primaryObjectId = treeViewNode.objectId || objectIds[0];
        if (primaryObjectId) {
            bimViewer.showObjectInExplorers(primaryObjectId);
            bimViewer.showObjectProperties(primaryObjectId);
        }
    });
}

export {
    DEFAULT_DOUBLE_CLICK_THRESHOLD,
    collectObjectIdsInSubtree,
    focusTreeNodeInViewer
};
