use crate::core::game_state::DispawnOnGameOver;
use bevy::prelude::*;

#[derive(Component, Default)]
#[require(DispawnOnGameOver)]
pub struct AnimationIndices {
    pub first: usize,
    pub last: usize,
}

impl AnimationIndices {
    pub fn change(&mut self, first: usize, second: usize) {
        self.first = first;
        self.last = second;
    }
}

#[derive(Component, Deref, DerefMut)]
#[require(DispawnOnGameOver)]
pub struct AnimationTimer(pub Timer);

pub fn animate_sprite(time: Res<Time>, mut query: Query<(&AnimationIndices, &mut AnimationTimer, &mut Sprite)>) {
    for (indices, mut timer, mut sprite) in &mut query {
        timer.tick(time.delta());

        if timer.just_finished()
            && let Some(atlas) = &mut sprite.texture_atlas
        {
            atlas.index = if atlas.index >= indices.last || atlas.index < indices.first {
                indices.first
            } else {
                atlas.index + 1
            };
        }
    }
}
