use bevy::{
    ecs::{archetype::Archetypes, component::Components, entity::Entities},
    prelude::*,
};
use shared::global_observer;

pub fn plugin(app: &mut App) {
    global_observer!(app, report_entity_components);
}

#[derive(Event)]
pub struct ReportEntityComponents(pub Entity);

fn report_entity_components(
    trigger: Trigger<ReportEntityComponents>,
    entities: &Entities,
    components: &Components,
    archetypes: &Archetypes,
) {
    let Some(location) = entities.get(trigger.event().0) else {
        warn!("failed to report entity components; had no location");
        return;
    };
    let Some(archetype) = archetypes.get(location.archetype_id) else {
        warn!("failed to report entity components; had no archetype");
        return;
    };

    let mut output = format!("Entity {:?} Components: ", trigger.event().0);
    for component in archetype.components() {
        if let Some(name) = components.get_name(component) {
            output.push_str(&format!("{name}, "));
        }
    }

    info!("{}; Caller: {}", output, trigger.caller());
}
