import Name from "../../../ecs/name/Name.js";
import { EntityNode } from "../../../ecs/parent/EntityNode.js";
import { copy_three_transform } from "../../../ecs/transform/copy_three_transform.js";
import { Transform } from "../../../ecs/transform/Transform.js";
import { ShadedGeometry } from "./ShadedGeometry.js";

/**
 *
 * @param {THREE.Object3D} root
 * @returns {EntityNode}
 */
export function three_object_to_entity_composition(root) {
    const node = new EntityNode();

    const node_transform = node.transform;

    // copy object transform
    copy_three_transform(node_transform, root);

    const entity = node.entity;

    const transform = new Transform();
    // initialize world transform
    transform.fromMatrix(root.matrixWorld.elements);

    entity.add(transform);
    entity.add(new Name(root.name));

    if (root.isMesh) {
        if (root.isSkinnedMesh) {
            console.error(`Skinned meshes are not supported`);
        }

        const sg = ShadedGeometry.from(root.geometry, root.material);

        if(root.customDepthMaterial !== undefined && root.customDepthMaterial !== null) {
            sg.depth_material = root.customDepthMaterial;
        }

        entity.add(sg);
    }

    const children = root.children;
    const child_count = children.length;

    for (let i = 0; i < child_count; i++) {
        const child = children[i];

        const child_node = three_object_to_entity_composition(child);

        node.addChild(child_node);
    }

    return node;
}
