using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class PlayerMovement_CharController : MonoBehaviour
{
    public float gravity = -9.81f;
    public float speed = 0;
    public CharacterController  controller = null;
    public Transform groundCheck = null;
    public float groundCheckRadius = 0;
    public LayerMask groundMask;
    public float jumpHeight;
    public AudioSource audio;
    private float vertical = 0;
    private float horizontal = 0;
    private bool isGrounded = true;
    private Vector3 velocity = new Vector3();

    private Vector3 dash;

    void Update()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundCheckRadius, groundMask);

        if(isGrounded && velocity.y < 0){
            velocity.y = -1f;
        }

        vertical = Input.GetAxisRaw("Vertical");
        horizontal = Input.GetAxisRaw("Horizontal");
        Vector3 move = (transform.right * horizontal + transform.forward * vertical).normalized + dash;
        if(move.magnitude == 0 || !isGrounded)
            audio.Stop();
        else if(!audio.isPlaying)
            audio.Play();
        controller.Move(move * speed * Time.deltaTime);
        if(Input.GetButtonDown("Jump") && isGrounded)
            velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
        velocity.y += gravity * Time.deltaTime;
        controller.Move(velocity*Time.deltaTime);
    }

    void OnDrawGizmos(){
        Gizmos.color = Color.white;
        Gizmos.DrawWireSphere(groundCheck.position, groundCheckRadius);
    }

    public void Dash(Vector3 direction, float speed, float duration){
        dash = new Vector3(direction.x, 0, direction.z)*speed;
        velocity.y = direction.y*speed*2;
        Invoke(nameof(StopDash), duration);
    }

    private void StopDash(){
        dash = Vector3.zero;
    }
}
