using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
public struct TraceData { 
    public string path;
    public string line;
}
public class LuaTraceWindow : EditorWindow
{
    Vector2 scrollPos = Vector2.zero;
    List<TraceData> traceDataList = new List<TraceData>();
    public string errorInfo = "";
    public static void  OpenTraceWindow(string errorInfo,string traceData)
    {
        LuaTraceWindow win = EditorWindow.GetWindow<LuaTraceWindow>();
        win.errorInfo = errorInfo;
        win.GetTraceDataList(traceData);
        win.titleContent = new GUIContent("Trace面板");
    }

    private void GetTraceDataList(string data)
    {
        string pattern = @"\[string\s+\""(.*?)\""\]:\d+"; 
        MatchCollection matches = Regex.Matches(data, pattern);

        foreach (Match match in matches)
        {

            string patternStr = @"\[string\s+\""([^\""]+)\""\]:(\d+)";
            Match matchResult = Regex.Match(match.Value, patternStr);

            if (matchResult.Success)
            {
                TraceData traceData;
                traceData.path = Path.Combine(Application.dataPath, "..", matchResult.Groups[1].Value) ; 
                traceData.line = matchResult.Groups[2].Value;
                traceDataList.Add(traceData);
            }
            else
            {
                UnityEngine.Debug.Log("No match found.");
            }
        }
    }
    [MenuItem("test/testTrace")]
     static void test()
     {
        string s = "stack traceback:\n\t[string \"util/UGuiUtil.lua\"]:119: in field \'addClickEvent\'\n\t[string \"ui/mainmap/MainMapUI.lua\"]:708: in method \'initStages\'\n\t[string \"ui/mainmap/MainMapUI.lua\"]:30: in method \'onLoad\'\n\t[string \"core/UILayer.lua\"]:230: in method \'show\'\n\t[string \"mod/map/main/MainMapScene.lua\"]:71: in method \'onLoad\'\n\t[string \"mod/Mod.lua\"]:228: in method \'afterLoadDepend\'\n\t[string \"mod/Mod.lua\"]:54: in upvalue \'finishCb\'\n\t[string \"core/Res.lua\"]:249: in function <[string \"core/Res.lua\"]:246>";
        OpenTraceWindow("",s);
     }

    private void OnGUI()
    {
        GUILayout.Label("Trace路径：");
        GUILayout.Label($"{errorInfo}");
        scrollPos = GUILayout.BeginScrollView(scrollPos);

        foreach (var item in traceDataList)
        {
            if (GUILayout.Button(item.path + ":" + item.line))
            {
                Process.Start("code", $"-g {item.path}:{item.line}");
            }
        }
        GUILayout.EndScrollView();
    }
}
