import {v3_distance_above_plane} from "../../vec3/v3_distance_above_plane.js";
import {aabb3_build_corners} from "./aabb3_build_corners.js";
import {aabb3_matrix4_project_by_corners} from "./aabb3_matrix4_project_by_corners.js";

const scratch_corners = new Float32Array(24);

/**
 * Figure out which side of a plane an Axis-Aligned Bounding Box lies, after applying transform matrix to it
 * 2,0,or -2; 2: above, -2 : below, 0 : intersects plane
 * @param {number} x0
 * @param {number} y0
 * @param {number} z0
 * @param {number} x1
 * @param {number} y1
 * @param {number} z1
 * @param {number} plane_normal_x
 * @param {number} plane_normal_y
 * @param {number} plane_normal_z
 * @param {number} plane_offset
 * @param {number[]|Float32Array} transform_matrix
 * @returns {number}
 */
export function aabb3_transformed_compute_plane_side(
    x0, y0, z0, x1, y1, z1,
    plane_normal_x, plane_normal_y, plane_normal_z, plane_offset,
    transform_matrix
) {
    // TODO consider transforming the plane instead?


    aabb3_build_corners(
        scratch_corners, 0,
        x0, y0, z0, x1, y1, z1
    );

    aabb3_matrix4_project_by_corners(
        scratch_corners,
        scratch_corners,
        transform_matrix
    );

    let has_above = false, has_below = false;

    for (let i = 0; i < 8; i++) {
        const i3 = i * 3;
        const x = scratch_corners[i3];
        const y = scratch_corners[i3 + 1];
        const z = scratch_corners[i3 + 2];

        if (v3_distance_above_plane(x, y, z, plane_normal_x, plane_normal_y, plane_normal_z, plane_offset)) {
            has_above = true;
        } else {
            has_below = true;
        }
    }

    let result = 0;

    if (has_above) {
        result += 2;
    }
    if (has_below) {
        result -= 2;
    }

    return result;
}
