use crate::{CombatStats, Player, SufferDamage};
use specs::prelude::*;

pub struct DamageSystem;

impl<'a> System<'a> for DamageSystem {
    type SystemData = (
        WriteStorage<'a, CombatStats>,
        WriteStorage<'a, SufferDamage>,
    );

    fn run(&mut self, data: Self::SystemData) {
        let (mut stats, mut damage) = data;

        for (mut stats, damage) in (&mut stats, &damage).join() {
            stats.hp -= damage.amount;
        }

        damage.clear();
    }
}

pub struct CleanupDead;

impl<'a> System<'a> for CleanupDead {
    type SystemData = (
        Entities<'a>,
        ReadStorage<'a, CombatStats>,
        ReadStorage<'a, Player>,
    );

    fn run(&mut self, (entities, stats, player): Self::SystemData) {
        let mut dead = Vec::new();

        for (entity, stats) in (&entities, &stats).join() {
            if stats.hp < 1 {
                if player.contains(entity) {
                    rltk::console::log("You are dead");
                } else {
                    dead.push(entity)
                }
            }
        }

        for e in dead {
            entities.delete(e).expect("Unable to delete");
        }
    }
}
