use bevy::prelude::*;

use crate::{hud::ScoreText, GameState};

pub struct ScorePlugin;

impl Plugin for ScorePlugin {
	fn build(&self, app: &mut App) {
		app.insert_resource(Score(0));
		app.insert_resource(ScoreTimer(Timer::from_seconds(1.0, TimerMode::Repeating)));
		app.add_systems(Update, score_tick.run_if(in_state(GameState::Playing)));
	}
}

#[derive(Resource)]
pub struct Score(pub u32);

#[derive(Resource, Deref, DerefMut)]
struct ScoreTimer(Timer);

fn score_tick(
	mut score: ResMut<Score>,
	time: Res<Time>,
	mut timer: ResMut<ScoreTimer>,
	mut score_text: Query<&mut Text, With<ScoreText>>,
) {
	let mut score_text = score_text.single_mut();
	timer.tick(time.delta());
	if timer.just_finished() {
		score.0 += 1;
		score_text.0 = format!("{}", score.0);
	}
}
