use bevy::{prelude::*, render::color::Color};
use bevy_rapier3d::prelude::*;
// use noise::{HybridMulti, NoiseFn, SuperSimplex};

pub const PLANET_RADIUS: f32 = 2_000.0;
pub const PLANET_HUE: f32 = 31.0;
pub const PLANET_SATURATION: f32 = 1.0;

#[derive(Component)]
pub struct CyberPlanet;

fn spawn_planet(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    //let color = Color::rgb(0.74, 0.5334, 0.176);

    let (mesh, shape) = gen_planet(2999.9);

    let pbody = (RigidBody::Fixed, Transform::from_xyz(0.0, 0.1, 0.0));

    let pcollide = (
        shape,
        Friction {
            coefficient: 1.2,
            ..Default::default()
        },
        Restitution::new(0.8),
        Transform::from_xyz(0.0, 1.0, 0.0),
        CollisionGroups::default(), // all colliders
        Ccd { enabled: true },
    );

    commands
        .spawn(PbrBundle {
            mesh: meshes.add(mesh),
            material: materials.add(StandardMaterial {
                base_color: Color::GREEN,
                ..Default::default()
            }),
            transform: Transform::from_xyz(0.0, 0.1, 0.0),
            ..Default::default()
        })
        .insert(pbody)
        .insert(pcollide)
        .insert(CyberPlanet);
}

pub struct CyberPlanetPlugin;
impl Plugin for CyberPlanetPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(Startup, spawn_planet);
    }
}

//---------------------------------------------------------------------
// utils
//---------------------------------------------------------------------

fn gen_planet(span: f32) -> (Mesh, Collider) {
    let mut mesh = Cuboid::new(span, 1.0, span);

    let collider = Collider::cuboid(span / 2.0, 0.5, span / 2.0);

    (mesh.mesh(), collider)
}
