using UnityEngine;
using System;
using System.Collections;

[RequireComponent(typeof(Animator))] 

public class IKTest : MonoBehaviour {
    
    [SerializeField] Animator animator;
    
	[SerializeField] bool _ikActive = false;

    public float Amount = 0;

    public Transform _ikTarget = null;
    public Transform _lookAtTarget = null;

    [Header("Left Right Override")]
    public Transform _ikOverrideRight = null;
    public Transform _ikOverrideLeft = null;
    


	[SerializeField] float _handOffset = .5f;

     //a callback for calculating IK
    void OnAnimatorIK()
    {
        if(animator) {
            
            //if the IK is active, set the position and rotation directly to the goal. 
            if(_ikActive) {

                // Set the look target position, if one has been assigned
                if(_lookAtTarget != null) {
                    animator.SetLookAtWeight(1);
                    animator.SetLookAtPosition(_lookAtTarget.position);
                }    

                // Set the right hand target position and rotation, if one has been assigned

                //Right
                if (_ikOverrideRight != null)
                {
                    animator.SetIKPositionWeight(AvatarIKGoal.RightHand, Amount);
                    animator.SetIKPosition(AvatarIKGoal.RightHand, _ikOverrideRight.TransformPoint(new Vector3(-_handOffset, 0, 0)));
                }
                else if (_ikTarget != null)
                {
                    animator.SetIKPositionWeight(AvatarIKGoal.RightHand, Amount);
                    animator.SetIKPosition(AvatarIKGoal.RightHand, _ikTarget.TransformPoint(new Vector3(-_handOffset, 0, 0)));
                }  


                //Left
                if (_ikOverrideLeft != null)
                {
                    animator.SetIKPositionWeight(AvatarIKGoal.LeftHand, Amount);
                    animator.SetIKPosition(AvatarIKGoal.LeftHand, _ikOverrideLeft.TransformPoint(new Vector3(-_handOffset, 0, 0)));
                }
                else if(_ikTarget != null)
                {
                    animator.SetIKPositionWeight(AvatarIKGoal.LeftHand, Amount);
                    animator.SetIKPosition(AvatarIKGoal.LeftHand, _ikTarget.TransformPoint(new Vector3(-_handOffset, 0, 0)));
                }

                
                
            }
            
            //if the IK is not active, set the position and rotation of the hand and head back to the original position
            else {          
                animator.SetIKPositionWeight(AvatarIKGoal.RightHand,0);
                animator.SetIKRotationWeight(AvatarIKGoal.RightHand,0); 
                animator.SetLookAtWeight(0);
            }
        }
    }    
}