using UnityEngine;

namespace pdinklag
{
    public static class AnimatorCommonExtensions
    {
        /// <summary>
        /// Copies the pose from another animator.
        /// </summary>
        /// <param name="anim">the destination</param>
        /// <param name="from">the source</param>
        /// <param name="rotation">copy local rotations</param>
        /// <param name="position">copy local positions</param>
        /// <param name="scale">copy local scales</param>
        public static void CopyPose(this Animator anim, Animator from, bool rotation, bool position, bool scale)
        {
            for (var i = 0; i < (int)HumanBodyBones.LastBone; i++)
            {
                var dst = anim.GetBoneTransform((HumanBodyBones)i);
                if (dst)
                {
                    var src = from.GetBoneTransform((HumanBodyBones)i);
                    if (src)
                    {
                        if (position) dst.localPosition = src.localPosition;
                        if (rotation) dst.localRotation = src.localRotation;
                        if (scale) dst.localScale = src.localScale;
                    }
                    else
                    {
                        Debug.LogWarning("Bone " + (HumanBodyBones)i + " exists on destination, but not in source...", dst);
                    }
                }
            }
        }

        /// <summary>
        /// Copies the human pose from another animator, using the avatars.
        /// </summary>
        /// <param name="anim">the destination</param>
        /// <param name="from">the source</param>
        /// <param name="rotation">copy local rotations</param>
        /// <param name="position">copy local positions</param>
        /// <param name="scale">copy local scales</param>
        public static void CopyHumanPose(this Animator anim, Animator from)
        {
            var pose = new HumanPose();
            var src = new HumanPoseHandler(from.avatar, from.transform);
            src.GetHumanPose(ref pose);
            var dst = new HumanPoseHandler(anim.avatar, anim.transform);
            dst.SetHumanPose(ref pose);
        }
    }
}
