import Vector3 from "../../Vector3.js";

const v0 = new Vector3();
const v1 = new Vector3();

/**
 *
 * @param {Vector3} result_point
 * @param {Vector3} result_direction
 * @param {number} a_normal_x
 * @param {number} a_normal_y
 * @param {number} a_normal_z
 * @param {number} a_constant
 * @param {number} b_normal_x
 * @param {number} b_normal_y
 * @param {number} b_normal_z
 * @param {number} b_constant
 * @return {boolean}
 */
export function plane3_intersect_plane(
    result_point,
    result_direction,
    a_normal_x, a_normal_y, a_normal_z, a_constant,
    b_normal_x, b_normal_y, b_normal_z, b_constant
) {

    /* direction is simply the cross product */
    v0._crossVectors(
        a_normal_x, a_normal_y, a_normal_z,
        b_normal_x, b_normal_y, b_normal_z
    );

    /* in this case we don't need to use 'determinant_m3' */
    const det = v0.lengthSqr();

    if (det !== 0) {
        /* (plane_b.xyz.cross(plane_c.xyz) * -plane_a[3] +
            *  plane_c.xyz.cross(plane_a.xyz) * -plane_b[3]) / det; */
        v1._crossVectors(
            b_normal_x, b_normal_y, b_normal_z,
            v0.x, v0.y, v0.z
        );

        const neg_a_constant = -a_constant;

        let r_p_x = v1.x * neg_a_constant;
        let r_p_y = v1.y * neg_a_constant;
        let r_p_z = v1.z * neg_a_constant;

        v1._crossVectors(
            v0.x, v0.y, v0.z,
            a_normal_x, a_normal_y, a_normal_z
        );

        const neg_b_constant = -b_constant;

        const inv_det = 1 / det;

        r_p_x += v1.x * neg_b_constant;
        r_p_y += v1.y * neg_b_constant;
        r_p_z += v1.z * neg_b_constant;

        r_p_x *= inv_det;
        r_p_y *= inv_det;
        r_p_z *= inv_det;

        // copy values
        result_point.set(r_p_x, r_p_y, r_p_z);
        result_direction.set(v0.x, v0.y, v0.z);

        return true;
    }

    // no intersection
    return false;
}
