using UnityEngine;

public class UnitRagdoll : MonoBehaviour {
    [SerializeField] private Transform ragdollRootBone;

    public void Setup(Transform originalRootBone) {
        MatchAllChildTransforms(originalRootBone, ragdollRootBone);
        ApplyExplosionToRagdoll(ragdollRootBone, Random.Range(300f, 1000f), 
            transform.position + new Vector3(Random.Range(-2,2), Random.Range(-2,2), Random.Range(-2,2)), Random.Range(20f, 40f));
    }

    private static void MatchAllChildTransforms(Transform root, Transform clone) {
        foreach (Transform child in root) {
            Transform cloneChild = clone.Find(child.name);
            if (cloneChild == null) continue;

            cloneChild.position = child.position;
            cloneChild.rotation = child.rotation;
            MatchAllChildTransforms(child, cloneChild);
        }
    }

    private static void ApplyExplosionToRagdoll(Transform root, float explosionForce, Vector3 explosionPosition, float explosionRadius) {
        foreach (Transform child in root) {
            if (!child.TryGetComponent(out Rigidbody childRigidbody)) continue;

            childRigidbody.AddExplosionForce(explosionForce, explosionPosition, explosionRadius);
            ApplyExplosionToRagdoll(child, explosionForce, explosionPosition, explosionRadius);
        }
    }
}
