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

/**
 * Safely untangles and removes a loop from the topology.
 * Removes it from the edge's radial cycle, unlinks it from the face cycle, and frees the memory.
 * @param {BinaryTopology} mesh
 * @param {number} loop Loop ID
 */
export function bt_loop_kill(mesh, loop) {
    // 1. Untangle from the edge's radial cycle
    const edge = mesh.loop_read_edge(loop);
    if (edge !== NULL_POINTER) {
        bt_radial_loop_remove(mesh, loop, edge);
    }

    // 2. Untangle from the face's loop cycle (doubly linked list)
    const next = mesh.loop_read_next(loop);
    const prev = mesh.loop_read_prev(loop);

    if (next !== NULL_POINTER && prev !== NULL_POINTER) {
        mesh.loop_write_next(prev, next);
        mesh.loop_write_prev(next, prev);
    }

    // 3. Update the face's base loop pointer if it was looking at this loop
    const face = mesh.loop_read_face(loop);
    if (face !== NULL_POINTER) {
        if (mesh.face_read_loop(face) === loop) {
            // If it was the only loop left, the face now has no loops
            mesh.face_write_loop(face, next === loop ? NULL_POINTER : next);
        }
    }

    mesh.loops.release(loop);
}