using System.Linq;
using UnityEngine;
using UnityEngine.UI;

public class Error : MonoBehaviour
{
    public static Error Instance;
    public TMPro.TMP_Text LogPanelContent;

    private void Awake()
    {
        Instance = this;
    }

    private static TMPro.TMP_Text _logPanelContent => Instance.LogPanelContent;
    private static int _messageMax = 50;
    private static int _messageCounter = 0;

    public static void Log(Color color, string message, float time = 5)
    {
        Log(message, color, time);
    }

    public static void Log(string message, Color color, float time = 5)
    {
        switch (color)
        {
            case Color c when c.Equals(Color.red):
                Debug.LogError(message);
                break;
            case Color c when c.Equals(Color.yellow):
                Debug.LogWarning(message);
                break;
            default:
                Debug.Log(message);
                break;
        }

        if (Instance == null || _logPanelContent == null) return;
        _messageCounter += 1;
        var log = _logPanelContent;
        var text = log.text + $"\n{_messageCounter}: <color=#{ColorUtility.ToHtmlStringRGB(color)}>{message}";
        var lines = text.Split('\n');
        if (lines.Length > _messageMax)
        {
            lines = lines.Skip(lines.Length - _messageMax).ToArray();
            text = string.Join("\n", lines);
        }
        log.text = text;
    }
}