use glc::vector::Vector4f;
use space_crush_common::components::{Position, Ship, Velocity};
use specs::{prelude::*, ReadStorage, System, World, WriteExpect};

use crate::resources::Geometry;

#[derive(Default)]
pub struct Ships;

#[derive(SystemData)]
pub struct ShipsData<'a> {
    geometry: WriteExpect<'a, Geometry>,
    position: ReadStorage<'a, Position>,
    velocity: ReadStorage<'a, Velocity>,
    ship: ReadStorage<'a, Ship>,
}

impl<'a> System<'a> for Ships {
    type SystemData = ShipsData<'a>;

    fn run(&mut self, data: Self::SystemData) {
        let ShipsData {
            mut geometry,
            position,
            velocity,
            ship,
        } = data;

        gl::enable(gl::BLEND);
        gl::blend_func(gl::SRC_ALPHA, gl::ONE);

        for (p, v, s) in (&position, &velocity, &ship).join() {
            geometry.render_lines(
                Vector4f::new(0.0, 0.0, 1.0, 0.2),
                &[p.pos, p.pos + v.dir * v.speed],
            );
            geometry.render_lines(
                Vector4f::new(1.0, 0.0, 0.0, 0.2),
                &[p.pos, p.pos + s.target_dir * 100.0],
            );
            geometry.render_lines(Vector4f::new(1.0, 1.0, 1.0, 0.2), &[p.pos, s.target_pos]);
        }

        gl::disable(gl::BLEND);
    }
}
