import Vector2 from "../../../core/geom/Vector2.js";
import Mesh from "../ecs/mesh/Mesh.js";

const tempPoint = new Vector2();

/**
 *
 * @param {SurfacePoint3} result
 * @param {Array.<Number>} entities
 * @param {EntityComponentDataset} ecd
 * @param {GraphicsEngine} ge
 * @param {Number} x
 * @param {Number} y
 * @returns {Number} entity number or -1 in case of failed test
 */
function modelHitTest(result, entities, ecd, ge, x, y) {
    tempPoint.set(x, y);

    ge.normalizeViewportPoint(tempPoint, tempPoint);

    let i = 0;
    const l = entities.length;

    for (; i < l; i++) {

        const entity = entities[i];

        const model = ecd.getComponent(entity, Mesh);

        if (model === null) {
            //entity no longer exists most likely
            continue;
        }

        /**
         *
         * @type {Intersection[]}
         */
        const hits = ge.intersectObjectUnderViewportPoint(tempPoint.x, tempPoint.y, model.mesh, true);

        // get hit


        if (hits.length > 0) {
            /**
             *
             * @type {Intersection}
             */
            const hit = hits[0];

            result.position.copy(hit.point);

            //TODO extract normal

            return entity;
        }

    }

    return -1;
}

export { modelHitTest };
