use bevy::prelude::*;
use bevy_sprite3d::Sprite3d;

#[derive(Component, Reflect, Deref, DerefMut)]
#[reflect(Component)]
pub struct AnimationTimer(Timer);

impl AnimationTimer {
    pub fn new(t: Timer) -> Self {
        Self(t)
    }
}

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

fn animate_sprite(
    mut commands: Commands,
    time: Res<Time>,
    mut query: Query<(Entity, &mut AnimationTimer, &mut Sprite3d)>,
) {
    for (e, mut timer, mut sprite_3d) in query.iter_mut() {
        timer.tick(time.delta());
        if timer.just_finished() {
            let length = sprite_3d.texture_atlas_keys.as_ref().unwrap().len();
            let atlas = sprite_3d.texture_atlas.as_mut().unwrap();

            if atlas.index < length - 1 {
                atlas.index = atlas.index.saturating_add(1) % length;
            } else {
                commands.entity(e).despawn();
            }
        }
    }
}
