import { line3_compute_segment_point_distance_sqr } from "../../../../line/line3_compute_segment_point_distance_sqr.js";

const scratch_vertex = new Float32Array(3);

/**
 * Shortest distance from a vertex to a given edge.
 *
 * @param {BinaryTopology} mesh
 * @param {number} v Vertex ID
 * @param {number} e Edge ID
 * @returns {number}
 */
export function bt_vertex_distance_to_edge(mesh, v, e) {

    const e_v1 = mesh.edge_read_vertex1(e);
    const e_v2 = mesh.edge_read_vertex2(e);

    if (e_v1 === v || e_v2 === v) {
        // vertex is on edge
        return 0;
    }

    mesh.vertex_read_coordinate(scratch_vertex, 0, v);

    const px = scratch_vertex[0];
    const py = scratch_vertex[1];
    const pz = scratch_vertex[2];

    mesh.vertex_read_coordinate(scratch_vertex, 0, e_v1);

    const ax = scratch_vertex[0];
    const ay = scratch_vertex[1];
    const az = scratch_vertex[2];

    mesh.vertex_read_coordinate(scratch_vertex, 0, e_v2);

    const bx = scratch_vertex[0];
    const by = scratch_vertex[1];
    const bz = scratch_vertex[2];

    const d2 = line3_compute_segment_point_distance_sqr(
        ax, ay, az,
        bx, by, bz,
        px, py, pz
    );

    return Math.sqrt(d2);
}