import { split_by_3 } from "../../../../../core/binary/split_by_3.js";
import { array_quick_sort_by_comparator } from "../../../../../core/collection/array/array_quick_sort_by_comparator.js";
import { v3_distance_sqr } from "../../../../../core/geom/vec3/v3_distance_sqr.js";

/**
 *
 * @param {number[]} triangles
 * @param {number} offset
 * @param {number} count
 * @param {number} point_x
 * @param {number} point_y
 * @param {number} point_z
 * @param morton_codes
 * @param bounds
 */
export function sort_triangles_by_distance_to_point(
    triangles, offset, count,
    morton_codes, bounds,
    point_x, point_y, point_z,
) {
    const bounds_x0 = bounds.x0;
    const bounds_y0 = bounds.y0;
    const bounds_z0 = bounds.z0;

    const bounds_scale_x = bounds.getExtentsX() / 1023;
    const bounds_scale_y = bounds.getExtentsY() / 1023;
    const bounds_scale_z = bounds.getExtentsZ() / 1023;

    array_quick_sort_by_comparator(triangles, (a, b) => {

        const morton_a = morton_codes[a];
        const morton_b = morton_codes[b];

        const ax = bounds_x0 + bounds_scale_x * split_by_3(morton_a);
        const ay = bounds_y0 + bounds_scale_y * split_by_3(morton_a >>> 1);
        const az = bounds_z0 + bounds_scale_z * split_by_3(morton_a >>> 2);

        const bx = bounds_x0 + bounds_scale_x * split_by_3(morton_b);
        const by = bounds_y0 + bounds_scale_y * split_by_3(morton_b >>> 1);
        const bz = bounds_z0 + bounds_scale_z * split_by_3(morton_b >>> 2);

        const delta_a = v3_distance_sqr(ax, ay, az, point_x, point_y, point_z);
        const delta_b = v3_distance_sqr(bx, by, bz, point_x, point_y, point_z);

        return delta_b - delta_a;
    }, undefined, offset, count - 1);

}