using UnityEngine;
using UnityEngine.InputSystem;

namespace StudyCase2
{
    public class ThirdCharacterController : MonoBehaviour
    {
        CharacterController characterController;
        InputActionAsset inputAction;
        Animator animator;
        Transform forward;
        Transform model;
        Cinemachine.CinemachineVirtualCamera vCam;
        public float moveSpeed = 5f;
        public float jumpSpeed = 2f;
        public float turnSpeed = 10f;
        public float gravity = 10f;
        Vector3 moveDir;
        Vector2 moveInput;
        private void Awake()
        {
            characterController = GetComponent<CharacterController>();
            forward = transform.Find("Forward");
            model = transform.Find("Model");
            animator = model.GetComponentInChildren<Animator>();
            vCam = transform.Find("Virtual Camera").GetComponent<Cinemachine.CinemachineVirtualCamera>();
            inputAction = Resources.Load<InputActionAsset>("PlayerInputActions");
            inputAction.FindAction("Move").started += OnMove;
            inputAction.FindAction("Move").performed += OnMove;
            inputAction.FindAction("Move").canceled += OnMove;
            inputAction.FindAction("Jump").performed += OnJump;
            inputAction.Enable();
        }
        private void Update()
        {
            moveDir = new Vector3(moveInput.x, moveDir.y, moveInput.y);
            forward.eulerAngles = new Vector3(0, vCam.transform.eulerAngles.y, 0);
            moveDir = forward.TransformDirection(moveDir);
            if (moveInput != Vector2.zero)
            {
                animator?.SetBool("Move", true);
                Quaternion target = Quaternion.LookRotation(new Vector3(moveDir.x, 0, moveDir.z));
                model.rotation = Quaternion.Slerp(model.rotation, target, turnSpeed * Time.deltaTime);
            }
            else animator?.SetBool("Move", false);
            if (!characterController.isGrounded)
                moveDir.y -= gravity * Time.deltaTime;
            characterController.Move(moveDir * moveSpeed * Time.deltaTime);
        }
        public void OnMove(InputAction.CallbackContext context)
        {
            if (characterController.isGrounded)
                moveInput = context.ReadValue<Vector2>();
            else moveInput = Vector2.zero;
        }
        public void OnJump(InputAction.CallbackContext context)
        {
            if (characterController.isGrounded)
            {
                moveDir.y = jumpSpeed;
            }
        }
    }
}
