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

public class Dash : MonoBehaviour
{
    public bool IsDashing { get; set; }

    bool canDash = true;

    float cooldownTimer = 2;
    float dashDuration = 0.25f;
    float dashForce = 75;

    PlayerController player;

    Coroutine dashCo;
    TrailRenderer tr;

    private void Awake()
    {
        player = GetComponent<PlayerController>();
        tr = GetComponent<TrailRenderer>();
        tr.enabled = false;
    }

    public void ActivateDash()
    {
        if (canDash == true)
        {
            DashCoSafetyWrapper();
        }
    }

    void DashCoSafetyWrapper()
    {
        if(dashCo != null)
        {
            StopCoroutine(dashCo);
        }

        dashCo = StartCoroutine(Dashing());
    }

    IEnumerator Dashing()
    {

        tr.enabled = true;
        IsDashing = true;
        canDash = false;

        float duration = dashDuration;

        Vector3 dir = new Vector3(player.controlInputs.InputVector.x, 0, player.controlInputs.InputVector.y);
        while (duration > 0)
        {
            duration -= Time.deltaTime;
            player.rigidBody.AddForce(dir * dashForce);
            yield return null;
        }

        IsDashing = false;
        tr.enabled = false;

        yield return new WaitForSeconds(cooldownTimer);

        canDash = true;
    }
}
