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

/**
 * Removes an edge from a vertex's disk cycle.
 * @see https://github.com/blender/blender/blob/afb0d411072db51b871607034befe3677f9fd82d/source/blender/bmesh/intern/bmesh_structure.cc#L162
 * @param {BinaryTopology} mesh
 * @param {number} e Edge ID
 * @param {number} v Vertex ID
 */
export function bt_disk_edge_remove(mesh, e, v) {
    const is_v1 = mesh.edge_read_vertex1(e) === v;

    const prev = is_v1 ? mesh.edge_read_v1_disk_prev(e) : mesh.edge_read_v2_disk_prev(e);
    const next = is_v1 ? mesh.edge_read_v1_disk_next(e) : mesh.edge_read_v2_disk_next(e);

    if (prev === e) {
        // This is the only edge in the cycle
        mesh.vertex_write_edge(v, NULL_POINTER);
    } else {

        const prev_is_v1 = mesh.edge_read_vertex1(prev) === v;

        if (prev_is_v1) {
            mesh.edge_write_v1_disk_next(prev, next);
        } else {
            mesh.edge_write_v2_disk_next(prev, next);
        }

        const next_is_v1 = mesh.edge_read_vertex1(next) === v;

        if (next_is_v1) {
            mesh.edge_write_v1_disk_prev(next, prev);
        } else {
            mesh.edge_write_v2_disk_prev(next, prev);
        }

        // If the vertex's entry pointer was looking at this edge, shift it
        if (mesh.vertex_read_edge(v) === e) {
            mesh.vertex_write_edge(v, next);
        }

    }
}