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

public class PlacementDisplay : MonoBehaviour
{
    [Header("Local Player")]
    [SerializeField] RacerCore m_localPlayer;

    [Header("Placement Display")]
    [SerializeField] TextMeshProUGUI m_placementText;

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

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

        if (m_debugChannel)
            m_debugChannel.Raise(this, "Subscribed to local player! Now listening for placement updates.");

        m_localPlayer.OnPlacementChanged += SetPlacementDisplay;
    }

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

        if (m_debugChannel)
            m_debugChannel.Raise(this, "Unsubscribed from local player! No longer listening for placement updates.");

        m_localPlayer.OnPlacementChanged -= SetPlacementDisplay;
    }

    private void Start()
    {
        if (!m_localPlayer)
            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! Now listening for placement updates.");

        m_localPlayer.OnPlacementChanged += SetPlacementDisplay;
    }

    void SetPlacementDisplay(int _place)
    {
        if (!m_placementText)
            return;

        string _placeText = _place.ToString();

        switch (_place)
        {
            case (1):
                _placeText += "st";
                break;
            case (2):
                _placeText += "nd";
                break;
            case (3):
                _placeText += "rd";
                break;
            default:
                _placeText += "th";
                break;
        }

        if (m_debugChannel)
            m_debugChannel.Raise(this, "Local player is now in " + _placeText + " place!");

        m_placementText.SetText(_placeText);
    }
}
