use crate::components::{Controlled, Velocity};
use crate::game::MyGame;
use crate::resources::KeySet;

use specs::RunNow;

pub struct Move;

impl<'a> specs::System<'a> for Move {
    type SystemData = (
        specs::ReadStorage<'a, Controlled>,
        specs::WriteStorage<'a, Velocity>,
        specs::Read<'a, KeySet>,
    );

    fn run(&mut self, (movable, mut velocity, keys): Self::SystemData) {
        use specs::Join;

        for (_, vel) in (&movable, &mut velocity).join() {
            vel.dx = 0.0;
            vel.dy = 0.0;

            if keys.contains(&winit::VirtualKeyCode::W) {
                vel.dy -= 2.0;
            }
            if keys.contains(&winit::VirtualKeyCode::A) {
                vel.dx -= 2.0;
            }
            if keys.contains(&winit::VirtualKeyCode::S) {
                vel.dy += 2.0;
            }
            if keys.contains(&winit::VirtualKeyCode::D) {
                vel.dx += 2.0;
            }
        }
    }
}

pub fn systems(game: &mut MyGame) {
    Move.run_now(&game.world);
}
