using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

[ExecuteInEditMode()]
public class StaminaBar : MonoBehaviour
{
    public PlayerController playerController;

    public Slider staminaBar;

    public float maxStamina = 100f;
    public float currentStamina;

    public float drainRate = 20f;
    public float regenRate = 5f;
    public float regenDelay = 20f;

    private float lastStaminaUseTime;

    private void Start()
    {
        playerController = GameObject.Find("Player").GetComponent<PlayerController>();
        if (playerController == null) Debug.LogError("StaminaBar: Can't find playerController");

        currentStamina = maxStamina;
        staminaBar.maxValue = maxStamina;
        staminaBar.value = currentStamina;
    }

    private void Update()
    {
        if (playerController.isRunning && currentStamina > 0)
        {
            currentStamina -= drainRate * Time.deltaTime;
            lastStaminaUseTime = Time.time;

            if(currentStamina < 0)
            {
                currentStamina = 0;
            }
        }
        else if(currentStamina < maxStamina && !playerController.isRunning)
        {
            if(Time.time >= lastStaminaUseTime + regenDelay)
            {
                currentStamina += regenRate * Time.deltaTime;

                if(currentStamina > maxStamina)
                {
                    currentStamina = maxStamina;
                }
            }
        }

        staminaBar.value = currentStamina;

        playerController.canRun = currentStamina <= 0 ? false : true;
        
    }
}
