using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using deVoid.Utils;
using TMPro;
using UnityEngine;

public class ActionLogText : MonoBehaviour
{
    static int _maxRows = 4;
    static List<string> _lines = new();
    static TMP_Text _text;

    void Awake()
    {
        _text = GetComponent<TMP_Text>();
    }

    public static void Add(string playerName, string logLine)
    {
        Color c = new Color(0.45f, 0.62f, 0.84f);
        var hex = ColorUtility.ToHtmlStringRGBA(c);
        string coloredName = $"<color=#{hex}>{playerName}</color>";

        string message = "";
        if (HasReplacableValue(logLine))
            message = string.Format(logLine, coloredName);
        else
            message = $"{coloredName} {logLine}";
       
        Signals.Get<ActionMessageSignal>().Dispatch(message);
        if (_text == null)
        {
            Debug.LogWarning("No ActionLogText object is in this scene to render actionlog entries.");
            return;
        }
        _lines.Add(logLine);
        if (_lines.Count > _maxRows)
            _lines.RemoveAt(0);

        StringBuilder b = new StringBuilder();
        foreach (var line in _lines)
            b.AppendLine(line);
        _text.SetText(b);
    }
    
    static bool HasReplacableValue(string s) =>  Regex.IsMatch(s, "{\\d+}");
}