import { BitSet } from "../../../../binary/BitSet.js";

/**
 *
 * @type {TopoTriangle[]}
 */
const neighbours = [];

/**
 *
 * @param {TopoTriangle[]} initial_set indices of triangles that make up initial set, these are triangles that we start from, they will also be included in the resulting set
 * @param {function(tri:TopoTriangle, prev:TopoTriangle):boolean} filter decides whether a triangle should be included or not
 * @returns {TopoTriangle[]} set of selected triangles, will include initial set as well
 */
export function mesh_flood_fill({
                                    initial_set,
                                    filter
                                }) {

    const closed = new BitSet();
    const open = [...initial_set];

    const result_set = [];

    while (open.length > 0) {
        const current = open.pop();

        closed.set(current.index, true);

        result_set.push(current);

        // get neighbours

        const neighbour_count = current.getEdgeNeighbours(neighbours, 0);

        for (let i = 0; i < neighbour_count; i++) {
            const neighbour_face = neighbours[i];

            if (closed.get(neighbour_face.index)) {
                continue;
            }

            if (!filter(neighbour_face, current)) {
                // rejected by filter
                continue;
            }

            if (open.includes(neighbour_face)) {
                // already included
                continue;
            }

            open.push(neighbour_face);
        }

    }

    return result_set;
}
