use bevy::{gltf::Gltf, prelude::*};

fn main() {
    App::new()
        .add_plugins((DefaultPlugins,))
        .add_systems(Update, (inspect, load_gltf))
        .run();
}

#[derive(Debug, Component)]
struct InspectScene;

fn inspect(
    mut events: EventReader<AssetEvent<Scene>>,
    current: Query<Entity, With<InspectScene>>,
    mut commands: Commands,
) {
    events.read().for_each(|event| match event {
        AssetEvent::LoadedWithDependencies { id } => {
            // Cleanup existing scenes
            current.iter().for_each(|e| {
                commands.entity(e).despawn_recursive();
            });

            // Spawn default GLTF scene
            commands.spawn((
                SceneBundle {
                    scene: Handle::Weak(id.clone()),
                    ..default()
                },
                InspectScene,
            ));
        }
        _ => (),
    });
}

fn load_gltf(
    mut events: EventReader<FileDragAndDrop>,
    server: Res<AssetServer>,
    mut handle: Local<Handle<Gltf>>,
) {
    events.read().for_each(|event| match event {
        FileDragAndDrop::DroppedFile { path_buf, .. } => {
            let p = path_buf
                .clone()
                .into_os_string()
                .into_string()
                .unwrap()
                .replace(
                    "D:\\Projects\\src\\gitea.elijah.run\\martian-chess\\assets\\",
                    "",
                );
            info!("Loading {:?}", p);
            *handle = server.load(p);
        }
        _ => warn!("ignored"),
    })
}
