using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
using Photon.Pun;

public class MotorChargeDisplay : MonoBehaviour
{
    [Header("Player")]
    [SerializeField] RacerCore m_localPlayer = null;

    [Header("UI References")]
    [SerializeField] Image m_barImage = null;
    [SerializeField] TextMeshProUGUI m_textDisplay = null;

    [Header("Settings")]
    [SerializeField] Gradient m_barFillColors = new Gradient();

    [Header("Testing")]
    [SerializeField] [Range(0, 1)] float m_currentPercentage = 0;

    private void OnValidate()
    {
        UpdateDisplay(m_currentPercentage);
    }

    private void OnEnable()
    {
        if (!m_localPlayer)
            return;

        m_localPlayer.Motor.OnChargeUpdate += UpdateDisplay;
    }

    private void OnDisable()
    {
        if (!m_localPlayer)
            return;

        m_localPlayer.Motor.OnChargeUpdate -= UpdateDisplay;
    }

    private void Start()
    {
        if (m_localPlayer)
            return;
        
        StartCoroutine(TryGetPlayer());
    }

    IEnumerator TryGetPlayer()
    {
        while (!m_localPlayer)
        {
            m_localPlayer = RacerCore.LocalRacer;

            yield return null;
        }

        m_localPlayer.Motor.OnChargeUpdate += UpdateDisplay;
    }

    void UpdateDisplay(float _perc)
    {
        transform.localScale = new Vector3(_perc, transform.localScale.y, 1);

        if (m_barImage)
            m_barImage.color = m_barFillColors.Evaluate(_perc);

        if (m_textDisplay)
            m_textDisplay.text = _perc == 0 ? "EMPTY" : Mathf.CeilToInt(_perc * 100).ToString() + "%";
    }
}
