use bevy::prelude::*;

#[macro_export]
macro_rules! global_observer {
    ($app:expr,$system:expr) => {{
        $app.world_mut()
            .add_observer($system)
            .insert(Name::new(stringify!($system)))
    }};
}

pub use global_observer;

pub fn plugin(app: &mut App) {
    app.add_systems(Update, global_observers);
}

fn global_observers(
    mut cmds: Commands,
    query: Query<Entity, (With<Observer>, Without<Children>, Added<Observer>)>,
    mut root: Local<Option<Entity>>,
) {
    if root.is_none() {
        let new_root = cmds.spawn(Name::new("Observers")).id();
        *root = Some(new_root);
    }

    let Some(root) = *root else {
        return;
    };

    for o in query.iter() {
        cmds.entity(root).add_child(o);
    }
}
