import { NULL_POINTER } from "../BinaryTopology.js";

/**
 * Find an existing edge between two vertices
 * NOTE: works without having to use a separate hash map, resulting in faster execution and smaller RAM requirement
 * @param {BinaryTopology} mesh
 * @param {number} v0
 * @param {number} v1
 * @returns {number} edge ID, or {@link NULL_POINTER} if no such edge exists
 */
export function bt_edge_get(mesh, v0, v1) {
    const first_edge = mesh.vertex_read_edge(v0);

    if (first_edge === NULL_POINTER) {
        return NULL_POINTER;
    }

    // iterate over all edges around the vertex
    let edge = first_edge;

    do {
        const edge_v1 = mesh.edge_read_vertex1(edge);
        const edge_v2 = mesh.edge_read_vertex2(edge);

        if (edge_v1 === v1 || edge_v2 === v1) {
            // found edge that connects between v0 and v1
            return edge;
        }

        if (edge_v1 === v0) {
            edge = mesh.edge_read_v1_disk_next(edge);
        } else if (edge_v2 === v0) {
            edge = mesh.edge_read_v2_disk_next(edge);
        } else {
            // invalid edge connection
            throw new Error('Invalid edge, not connected to first vertex');
        }

    } while (edge !== first_edge);

    return NULL_POINTER;
}
