use std::f32::consts::PI;

use bevy::{pbr::CascadeShadowConfigBuilder, prelude::*};

#[derive(Resource)]
struct AnimationClips(Vec<Handle<AnimationClip>>);

fn main() {
    App::new()
        .add_plugins(DefaultPlugins.set(WindowPlugin {
            primary_window: Some(Window {
                title: "Animation WTF".into(),
                resolution: (640., 480.).into(),
                ..default()
            }),
            ..default()
        }))
        .add_startup_system(init)
        .add_system(spawn_animation)
        .run();
}

fn init(mut commands: Commands, server: Res<AssetServer>) {
    // Load gltf/animation assets
    commands.insert_resource(AnimationClips(vec![
        server.load("models/monkey-nod.glb#Animation0")
    ]));

    commands
        .spawn(SpatialBundle { ..default() })
        .with_children(|parent| {
            // spawn camera
            parent.spawn(Camera3dBundle {
                transform: Transform::from_xyz(10.0, 10.0, 15.0).looking_at(Vec3::ZERO, Vec3::Y),
                ..default()
            });

            parent.spawn(DirectionalLightBundle {
                transform: Transform::from_rotation(Quat::from_euler(
                    EulerRot::ZYX,
                    0.0,
                    1.0,
                    -PI / 4.0,
                )),
                directional_light: DirectionalLight {
                    shadows_enabled: true,
                    ..default()
                },
                cascade_shadow_config: CascadeShadowConfigBuilder {
                    first_cascade_far_bound: 20.0,
                    maximum_distance: 40.0,
                    ..default()
                }
                .into(),
                ..default()
            });

            parent.spawn(SceneBundle {
                scene: server.load("models/monkey-nod.glb#Scene0"),
                ..default()
            });
        });
}

fn spawn_animation(
    animations: Res<AnimationClips>,
    mut player: Query<&mut AnimationPlayer>,
    mut done: Local<bool>,
) {
    if !*done {
        if let Ok(mut player) = player.get_single_mut() {
            player.play(animations.0[0].clone_weak()).repeat();
            *done = true;
        }
    }
}
