import { assert } from "../../../core/assert.js";
import Vector3 from "../../../core/geom/Vector3.js";
import { SurfacePoint3 } from "../../../core/geom/3d/SurfacePoint3.js";
import Vector2 from "../../../core/geom/Vector2.js";

/**
 *
 * @param {number} x
 * @param {number} y
 * @param {GraphicsEngine} graphicsEngine
 * @param {Terrain} terrain
 * @param {function(gridPosition:Vector2,worldPosition:Vector3,normal:Vector3)} callback
 */
export function pick(x, y, graphicsEngine, terrain, callback) {

    assert.isNumber(x, 'x');
    assert.isNumber(y, 'y');

    assert.defined(terrain, 'terrain');
    assert.notNull(terrain, 'terrain');

    assert.isFunction(callback, 'callback');

    const vSource = new Vector3(x, y, 0);
    const vTarget = new Vector3();

    graphicsEngine.normalizeViewportPoint(vSource, vSource);
    graphicsEngine.viewportProjectionRay(vSource.x, vSource.y, vSource, vTarget);

    const surfacePoint3 = new SurfacePoint3();

    const hitFound = terrain.raycastFirstSync(surfacePoint3, vSource.x, vSource.y, vSource.z, vTarget.x, vTarget.y, vTarget.z);

    if (!hitFound) {
        // nothing found
    } else {

        const gridPosition = new Vector2();
        terrain.mapPointWorld2Grid(surfacePoint3.position, gridPosition);
        gridPosition._add(0.5, 0.5);
        callback(gridPosition, surfacePoint3.position, surfacePoint3.normal);
    }

}
