using System.Collections;
using UnityEngine;
using UnityEngine.UI;

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

    [Header("UI References")]
    [SerializeField] Image m_itemImage = null;

    [Header("Default Sprite")]
    [SerializeField] Sprite m_defaultSprite = null;

    [Header("Debug")]
    [SerializeField] DebugChannelSO m_debugChannel;

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

        if (m_debugChannel)
            m_debugChannel.Raise(this, "Subscribed to local player! Awaiting item display updates.");

        m_localPlayer.Items.OnItemDisplayUpdate += UpdateDisplay;
    }

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

        if (m_debugChannel)
            m_debugChannel.Raise(this, "Unsubscribed from local player! No longer awaiting item display updates.");

        m_localPlayer.Items.OnItemDisplayUpdate -= UpdateDisplay;
    }

    private void Start()
    {
        m_itemImage = GetComponent<Image>();

        UpdateDisplay(null);

        if (m_localPlayer)
            return;

        StartCoroutine(TryGetPlayer());
    }

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

            yield return null;
        }

        if (m_debugChannel)
            m_debugChannel.Raise(this, "Subscribed to local player! Awaiting item display updates.");

        m_localPlayer.Items.OnItemDisplayUpdate += UpdateDisplay;
    }

    void UpdateDisplay(Sprite _sprite)
    {
        if (!m_itemImage)
            return;

        m_itemImage.sprite = _sprite == null ? m_defaultSprite : _sprite;

        if (m_debugChannel)
            m_debugChannel.Raise(this, "Item display set to " + m_itemImage.sprite.ToString());
    }
}
