import { INVALID_NEIGHBOUR } from "../../TetrahedralMesh.js";
import { array_range_equal_strict } from "../../../../../collection/array/array_range_equal_strict.js";

export function debug_validate_cavity_boundary(mesh, cavity) {
    let valid = true;
    const problems = [];

    if (!validate_cavity_boundary(cavity, problem => problems.push(problem))) {
        valid = false;
    }

    if (!valid) {
        debugger;
    }

    return valid;
}

/**
 *
 * @param {Cavity} cavity
 * @param {function(problem:string):*} consumer
 * @returns {boolean}
 */
export function validate_cavity_boundary(cavity, consumer) {
    let valid = true;

    const boundary = cavity.__boundary;
    const boundary_size = cavity.__boundary_size;

    for (let i = 0; i < boundary_size; i++) {
        const encoded_tet_0 = boundary[i * 5 + 4];

        if (encoded_tet_0 === INVALID_NEIGHBOUR) {
            // this is "no neighbour" marker, there are allowed to be many of these
            continue;
        }

        for (let j = i + 1; j < boundary_size; j++) {

            const encoded_tet_1 = boundary[j * 5 + 4];

            if (encoded_tet_0 === encoded_tet_1) {
                valid = false;

                let message = `Duplicate neighbourhood ${encoded_tet_0} (tet=${(encoded_tet_0 >> 2)}, vert=${(encoded_tet_0 & 3)}), boundary elements [${i}, ${j}]`;

                if (!array_range_equal_strict(boundary, i * 5, boundary, j * 5, 4)) {
                    // boundary definitions are divergent
                    message += `, boundary definitions are divergent - ${i}:[${boundary.slice(i * 5, i * 5 + 4).join(', ')}], ${j}:[${boundary.slice(j * 5, j * 5 + 4).join(', ')}]`
                }

                consumer(message);
            }

        }
    }

    return valid;
}
