import { Transform } from "../../../ecs/transform/Transform.js";
import { MeshEvents } from "./MeshEvents.js";

/**
 *
 * @param {Mesh} component
 * @param {THREE.Object3D} mesh
 * @param {number} entity
 */
export function applyComponentPropertiesToThreeObject(component, mesh, entity) {
    mesh.traverse(o => {
        o.castShadow = component.castShadow;
        o.receiveShadow = component.receiveShadow;
    });

    /*
        disable auto updates. We know when transform changes and thus we can avoid unnecessary matrix computations
        @see https://threejs.org/docs/index.html#api/core/Object3D.matrixWorldNeedsUpdate
     */
    mesh.matrixWorldNeedsUpdate = false;

    if (component.opacity === 0) {
        mesh.visible = false;
    }

    mesh.__meep_ecs_component = component;
    mesh.__meep_ecs_entity = entity;

}

/**
 *
 * @param {EntityComponentDataset} dataset
 * @param {number} entity
 * @param {Mesh} component
 * @param {Object3D} mesh
 */
export function setMesh(dataset, entity, component, mesh) {
    applyComponentPropertiesToThreeObject(component, mesh, entity);

    component.mesh = mesh;

    const transform = dataset.getComponent(entity, Transform);

    if (transform !== undefined) {
        // transform component found, apply transform
        component.internalApplyTransform(transform);
    }

    // scene.add(object);
    dataset.sendEvent(entity, MeshEvents.DataSet, {
        component,
        entity
    });
}
