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

/**
 * Adds a loop to an edge's radial cycle.
 * @param {BinaryTopology} mesh
 * @param {number} loop Loop ID
 * @param {number} edge Edge ID
 */
export function bt_radial_loop_add(mesh, loop, edge) {
    // Associate the loop with the edge
    mesh.loop_write_edge(loop, edge);

    const base_loop = mesh.edge_read_loop(edge);

    if (base_loop === NULL_POINTER) {
        // First loop on this edge
        mesh.edge_write_loop(edge, loop);
        mesh.loop_write_radial_next(loop, loop);
        mesh.loop_write_radial_prev(loop, loop);
    } else {
        // Splice into existing cycle just before the base_loop
        const base_prev = mesh.loop_read_radial_prev(base_loop);

        // Link base_prev -> loop
        mesh.loop_write_radial_next(base_prev, loop);
        mesh.loop_write_radial_prev(loop, base_prev);

        // Link loop -> base_loop
        mesh.loop_write_radial_next(loop, base_loop);
        mesh.loop_write_radial_prev(base_loop, loop);
    }
}