use rapier_testbed3d::TestbedViewer;
use rapier3d::prelude::*;

pub async fn run(viewer: &mut TestbedViewer) -> anyhow::Result<()> {
    /*
     * World
     */
    let mut world = PhysicsWorld::new();

    /*
     * Create the balls
     */
    let num = 30;
    let rad = 1.0;

    let shift = rad * 6.0 + 1.0;
    let centerx = shift * (num as f32) / 2.0;
    let centery = shift * (num as f32) / 2.0;
    let centerz = shift * (num as f32) / 2.0;

    for i in 0..num {
        for j in 0usize..num {
            for k in 0..num {
                let x = i as f32 * shift - centerx;
                let y = j as f32 * shift - centery;
                let z = k as f32 * shift - centerz;

                // Build the rigid body.
                let velocity = Vec3::new(
                    rand::random::<f32>() - 0.5,
                    rand::random::<f32>() - 0.5,
                    rand::random::<f32>() - 0.5,
                ) * 30.0;
                let rigid_body = RigidBodyBuilder::new(RigidBodyType::KinematicVelocityBased)
                    .translation(Vec3::new(x, y, z))
                    .linvel(velocity);
                let collider = ColliderBuilder::ball(rad);
                let _ = world.insert(rigid_body, collider);
            }
        }
    }

    /*
     * Set up the testbed.
     */
    viewer.set_world(&mut world);
    viewer.look_at(Vec3::new(100.0, 100.0, 100.0), Vec3::ZERO);

    while viewer.render_frame(&mut world).await {
        if viewer.simulating() {
            world.step();

            for (_, rb) in world.bodies.iter_mut() {
                let mut linvel = rb.linvel();

                for dim in 0..3 {
                    if (linvel[dim] > 0.0 && rb.translation()[dim] > (shift * num as f32) / 2.0)
                        || (linvel[dim] < 0.0
                            && rb.translation()[dim] < -(shift * num as f32) / 2.0)
                    {
                        linvel[dim] = -linvel[dim];
                    }
                }

                rb.set_linvel(linvel, false);
            }
        }
    }
    Ok(())
}
