use bevy::prelude::*;

pub struct UtilPlugin;

impl Plugin for UtilPlugin {
    fn build(&self, app: &mut App) {
        app.register_type::<SpriteLoader>()
            .add_systems(PostUpdate, load_sprite);
    }
}

/// Automatically sets the `Sprite` components `image` to given asset path upon being added.
///
/// Can be used to set default sprite in required components without having access to AssetServer.
#[derive(Clone, Debug, Default, Component, Reflect)]
#[reflect(Component)]
#[require(Sprite)]
pub struct SpriteLoader(pub String);

impl SpriteLoader {
    pub fn from(path: impl Into<String>) -> Self {
        Self(path.into())
    }
}

pub fn load_sprite(
    mut sprite_query: Query<(&mut Sprite, &SpriteLoader), Added<SpriteLoader>>,
    assets: Res<AssetServer>,
) {
    for (mut sprite, loader) in sprite_query.iter_mut() {
        sprite.image = assets.load(&loader.0);
    }
}
