use bevy::prelude::*;

use super::velocity::Velocity;

pub struct AnimationPlugin;

impl Plugin for AnimationPlugin {
	fn build(&self, app: &mut App) {
		app.add_systems(FixedUpdate, animation_tick);
	}
}

#[derive(Component, Default)]
pub struct SpriteAnimation {
	pub first: usize,
	pub last: usize,
	pub timer: Timer,
}

impl SpriteAnimation {
	pub fn new(last: usize, timer: Timer) -> Self {
		Self {
			first: 0,
			last,
			timer,
		}
	}
}

// #[derive(Component, Default, Deref, DerefMut)]
// pub struct AnimationTimer(pub Timer);

fn animation_tick(
	time: Res<Time>,
	mut query: Query<(&mut Sprite, &mut SpriteAnimation, &Velocity)>,
) {
	for (mut sprite, mut anim, velocity) in &mut query {
		let Some(atlas) = &mut sprite.texture_atlas
		else {
			continue;
		};

		if velocity.length() > 0.0 {
			anim.timer.tick(time.delta());
			if anim.timer.just_finished() {
				atlas.index = if atlas.index == anim.last {
					anim.first
				}
				else {
					atlas.index + 1
				}
			}
		}
	}
}
