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

[Preserve]
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;

    [Preserve]
    private Queue<string> logQueue = new Queue<string>();

    [Preserve]
    private bool isDirty = false;

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

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

    [Preserve]
    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;
    }

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


    [Preserve]
    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 实际高度
    [Preserve]
    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;
    }


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

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