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 = world.resources.physics.add_rigid_body(rapier_rigid_body);
    rigid_body_component.handle = Some(rapier_handle.into());

    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 = world
            .resources
            .physics
            .add_collider(rapier_collider, rapier_handle);
        collider_component.handle = Some(rapier_collider_handle.into());
        world.set_collider(entity, collider_component);
    }

    world.set_rigid_body(entity, rigid_body_component);
}
