using System.ComponentModel;
using UnityEngine;
using UnityEngine.UI;

public class Stamina : MonoBehaviour
{
    public float maxStamina;
    private float currentStamina;
    bool canSprint = true;
    bool isSprinting = false;

    public Slider staminaBar;
    public Gradient staminaBarGradient;
    private Image fillImage;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        if (currentStamina == 0)
        {
            currentStamina = 1;
        }
        fillImage = staminaBar.fillRect.GetComponent<Image>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.LeftShift) && canSprint) //spend stamina
        {
            isSprinting = true;
            currentStamina = Mathf.Max(0, currentStamina - Time.deltaTime);
        }
        else //regenerate stamina
        {
            isSprinting = false;
            currentStamina = Mathf.Min(maxStamina, currentStamina + Time.deltaTime / 2f);
        }

        if (currentStamina == 0) //trigger the cd
        {
            canSprint = false;
        }

        if (!canSprint && currentStamina == maxStamina) //stamina regenerated
        {
            canSprint = true;
        }

        staminaBar.value = currentStamina/maxStamina;
        fillImage.color = staminaBarGradient.Evaluate(staminaBar.value);
    }

    public float GetCurrentStamina()
    {
        return currentStamina;
    }

    public bool GetCanSprint()
    {
        return canSprint;
    }

    public bool GetIsSprinting()
    {
        return isSprinting;
    }

    public void Reinit(float currentStamina, bool canSprint)
    {
        this.currentStamina = currentStamina;
        this.canSprint = canSprint;
    }
}
