use crate::{global_observer, hitpoints::Hit, physics_layers::GameLayer};
use avian3d::prelude::*;
use bevy::prelude::*;

#[derive(Event, Debug)]
pub struct Explosion {
    pub position: Vec3,
    pub radius: f32,
    pub damage: u32,
}

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

fn on_explosion(
    explosion: Trigger<Explosion>,
    mut commands: Commands,
    spatial_query: SpatialQuery,
) {
    let explosion = explosion.event();
    let intersections = {
        spatial_query.shape_intersections(
            &Collider::sphere(explosion.radius),
            explosion.position,
            Quat::default(),
            &SpatialQueryFilter::default().with_mask(LayerMask(
                GameLayer::Npc.to_bits() | GameLayer::Player.to_bits(),
            )),
        )
    };

    for entity in intersections.iter() {
        if let Ok(mut e) = commands.get_entity(*entity) {
            e.trigger(Hit {
                damage: explosion.damage,
            });
        }
    }
}
