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

public class LogViewer : MonoBehaviour
{
    [Header("UI References")]
    public Text logText;
    public ScrollRect scrollRect;

    [Header("Settings")]
    public int maxLines = 1000;
    public bool autoScroll = true;
    public int lineHeight = 33;

    private Queue<string> logQueue = new Queue<string>();
    private bool isDirty = false;

    void OnEnable()
    {
        Application.logMessageReceived += HandleLog;
    }

    void OnDisable()
    {
        Application.logMessageReceived -= HandleLog;
    }

    void HandleLog(string logString, string stackTrace, LogType type)
    {
        string time = System.DateTime.Now.ToString("HH:mm:ss");
        string formattedLog = $"[{time}] {logString}";
        logQueue.Enqueue(formattedLog);
        isDirty = true;
    }

    void Update()
    {
        if (isDirty)
        {
            UpdateLogText();
            isDirty = false;
        }
    }


    void UpdateLogText()
    {
        if (logText == null || scrollRect == null)
        {
            Debug.LogWarning("LogViewer: 未绑定 logText 或 scrollRect");
            return;
        }

        // 限制最大行数
        while (logQueue.Count > maxLines)
        {
            logQueue.Dequeue();
        }

        // 拼接日志
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        foreach (var log in logQueue)
        {
            sb.AppendLine(log);
        }

        logText.text = sb.ToString();

        // ✅ 动态计算 Text 实际高度
        float preferredHeight = CalculateTextHeight(logText.text, logText);
        RectTransform contentRect = logText.GetComponent<RectTransform>().parent as RectTransform;
        if (contentRect != null)
        {
            contentRect.sizeDelta = new Vector2(contentRect.sizeDelta.x, Mathf.Max(preferredHeight, 500));
        }

        // 自动滚动到底部
        if (autoScroll)
        {
            Canvas.ForceUpdateCanvases();
            StartCoroutine(ScrollToBottom());
        }
    }

    // ✅ 计算 Text 实际高度
    float CalculateTextHeight(string text, Text textComponent)
    {
        if (string.IsNullOrEmpty(text))
            return 0;

        var style = textComponent.GetGenerationSettings(textComponent.rectTransform.rect.size);
        var height = textComponent.cachedTextGenerator.GetPreferredHeight(text, style);
        return height / textComponent.pixelsPerUnit;
    }


    System.Collections.IEnumerator ScrollToBottom()
    {
        yield return null; // 等待一帧
        scrollRect.verticalNormalizedPosition = 0f;
    }

    public void ClearLogs()
    {
        logQueue.Clear();
        if (logText != null)
        {
            logText.text = "";
        }
    }
}