use glam::Vec3;

use crate::utility::input::InputState;
use crate::world::World;

pub fn player_input_system(world: &mut World, input_state: &InputState)
{
    let Some((_, camera)) = world.active_camera()
    else
    {
        return;
    };

    let forward = camera.get_forward_horizontal();
    let right = camera.get_right_horizontal();

    let players = world.player_tags.all();

    for player in players
    {
        world.inputs.with_mut(player, |input_component| {
            let mut local_input = Vec3::ZERO;

            if input_state.w
            {
                local_input.z += 1.0;
            }
            if input_state.s
            {
                local_input.z -= 1.0;
            }
            if input_state.a
            {
                local_input.x -= 1.0;
            }
            if input_state.d
            {
                local_input.x += 1.0;
            }

            let move_direction = if local_input.length_squared() > 0.0
            {
                (forward * local_input.z + right * local_input.x).normalize()
            }
            else
            {
                Vec3::ZERO
            };

            input_component.move_direction = move_direction;
            input_component.jump_pressed = input_state.space;
            input_component.jump_just_pressed = input_state.space_just_pressed;
            input_component.roll_just_pressed = input_state.roll_just_pressed;
            input_component.parry_i_just_pressed = input_state.i_just_pressed;
            input_component.parry_j_just_pressed = input_state.j_just_pressed;
            input_component.parry_l_just_pressed = input_state.l_just_pressed;
        });
    }
}
