using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerJump : MonoBehaviour
{
    [SerializeField] private InputActionReference jump;
    [SerializeField] private float forceValue = 5f;
    [SerializeField] private GameObject playerGround;
    [SerializeField] private float groundRayOffset = 0.1f;
    [SerializeField] private float groundRayDistanceThreshold = 0.001f;
    //[SerializeField] private Animator animator;

    private Rigidbody rb;
    private CapsuleCollider collider;
    private BoxCollider boxCollider;
    private bool isJumping = false;
    private bool isGrounded = true;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        collider = GetComponent<CapsuleCollider>();
        boxCollider = playerGround.GetComponent<BoxCollider>();
        jump.action.Enable();
        jump.action.performed += OnJump;
        StartCoroutine(GroundCheck());
    }

    void OnJump(InputAction.CallbackContext context)
    {
        if (!isGrounded || isJumping)
        {
            return;
        }

        StartCoroutine(JumpControlFlow());

    }
    // Update is called once per frame
    void Update()
    {
        //animator.SetBool("Jumping", isJumping);
    }

    IEnumerator GroundCheck()
    {
        while (true)
        {
            float bottomOfCollider = collider.bounds.min.y;
            Vector3 newPlayerGroundPosition = new Vector3(playerGround.transform.position.x, bottomOfCollider,
                playerGround.transform.position.z);
            playerGround.transform.position = newPlayerGroundPosition;

            Vector3 rayCastOrigin = new Vector3(playerGround.transform.position.x, playerGround.transform.position.y + groundRayOffset,
                playerGround.transform.position.z);

            Vector3 playerGroundExtents = playerGround.transform.lossyScale;

            bool isHitting = Physics.BoxCast(rayCastOrigin, playerGroundExtents / 2, -transform.up, out RaycastHit hit, playerGround.transform.rotation);
            if (isHitting && hit.distance <= groundRayOffset + groundRayDistanceThreshold)
            {
                isGrounded = true;
                isJumping = false;
            }

            else
            {
                isGrounded = false;
            }
            yield return null;
        }
    }

    IEnumerator JumpControlFlow()
    {
        rb.AddForce(Vector3.up * forceValue, ForceMode.Impulse);

        while (isGrounded)
        {
            yield return null;
        }
        isJumping = true;

        boxCollider.enabled = true;
        yield return null;
    }
}
