use crate::ecs::physics::resources::{physics_world_add_collider, physics_world_add_rigid_body};
use crate::ecs::world::World;
use crate::ecs::world::components::LocalTransform;
use freecs::Entity;

use super::super::components::{PrefabCollider, PrefabRigidBody};

pub(super) fn apply_prefab_physics(
    world: &mut World,
    entity: Entity,
    prefab_rigid_body: &PrefabRigidBody,
    prefab_collider: Option<&PrefabCollider>,
    local_transform: LocalTransform,
) {
    let mut rigid_body_component =
        super::super::components::prefab_rigid_body_to_component(prefab_rigid_body);
    rigid_body_component.translation = local_transform.translation.into();
    let quat = local_transform.rotation;
    rigid_body_component.rotation = [quat.i, quat.j, quat.k, quat.w];

    let rapier_rigid_body = rigid_body_component.to_rapier_rigid_body();
    let rapier_handle =
        physics_world_add_rigid_body(&mut world.resources.physics, rapier_rigid_body);
    rigid_body_component.handle = Some(crate::ecs::physics::types::rigid_body_handle_from_rapier(
        rapier_handle,
    ));

    if let Some(prefab_collider) = prefab_collider {
        let mut collider_component =
            super::super::components::prefab_collider_to_component(prefab_collider);
        let rapier_collider = collider_component.to_rapier_collider();
        let rapier_collider_handle = physics_world_add_collider(
            &mut world.resources.physics,
            rapier_collider,
            rapier_handle,
        );
        collider_component.handle = Some(crate::ecs::physics::types::collider_handle_from_rapier(
            rapier_collider_handle,
        ));
        world.core.set_collider(entity, collider_component);
    }

    world.core.set_rigid_body(entity, rigid_body_component);
}
