import { assert } from "../../../assert.js";
import { tm_vert_kill } from "./tm_vert_kill.js";

/**
 * Splice vertex
 * Merges two vertices into one, source into destination, removing source.
 * NOTE: source vertex is deleted in the process
 *
 * @param {TopoMesh} mesh
 * @param {TopoVertex} destination
 * @param {TopoVertex} source
 * @returns {boolean}
 */
export function tm_vert_splice(mesh, destination, source) {
    if (destination === source) {
        // already spliced
        return false;
    }

    assert.defined(source, 'victim');
    assert.notNull(source, 'victim');
    assert.equal(source.isTopoVertex, true, "victim.isTopoVertex !== true");
    assert.notEqual(destination, source, "cannot replace self");

    const faces = source.faces;
    const face_count = faces.length;

    let i = 0;

    for (; i < face_count; i++) {
        // take over the victim's faces
        const face = faces.pop();


        // face.computeNormal(); // DEBUG
        face.replaceVertex(source, destination);

        destination.addUniqueFace(face);

        // face.computeNormal(); // DEBUG
    }

    const edges = source.edges;
    const edge_count = edges.length;

    // const destination_edges = destination.edges;

    for (i = 0; i < edge_count; i++) {
        // take over the victim's edges
        const edge = edges.pop();

        edge.replaceVertex(source, destination);
        //
        // for (let j = 0; j < destination_edges.length; j++) {
        //     destination_edges[j]
        // }

        destination.addUniqueEdge(edge);
    }

    tm_vert_kill(mesh, source);

    return true;
}
