using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using XGame.Editor.Asset;

namespace FL.Editor.Tests
{
    public static class TestString
    {
        [MenuItem("Test/String/DeSerialization")]
        public static void DeSerialization()
        {
            var filePath = PathDefine.DefaultOutputPath + "/config.bytes";
            if (!File.Exists(filePath))
            {
                return;
            }
            //FileStream fileStream = File.OpenRead(filePath);
            var text = File.ReadAllText(filePath);
            const char openBracket = '[';
            const char closeBracket = ']';
            const char openBrace = '{';
            const char closeBrace = '}';
            Regex regex = new Regex(@"Config/(.+?)\.json");
            var result = regex.Matches(text);
            var regCount = result.Count;
            Debug.Log($"Regex count:{regCount}");
            for(var regIdx = 0; regIdx < regCount; regIdx++)
            {
                var match = result[regIdx];
                Debug.Log($"match:{match.Value} index:{match.Index} value1:{match.Groups[1].Value}");
                var startIndex = match.Index + match.Value.Length;
                var openBracketIdx = text.IndexOf(openBracket, startIndex);
                var openBraceIdx = text.IndexOf(openBrace, startIndex);
                //两个值取小的
                var openIdx = openBracketIdx < openBraceIdx ? openBracketIdx : openBraceIdx;
                var closeChar = openBracketIdx < openBraceIdx ? closeBracket : closeBrace;
                int closeIdx;
                if (regIdx < regCount - 1)
                { // 
                    var nextMatch = result[regIdx + 1];
                    closeIdx = text.IndexOfReverse(closeChar, nextMatch.Index - 1);
                }
                else
                { //最后一个json
                    closeIdx = text.IndexOfReverse(closeChar);
                }
                if (closeIdx <= openIdx)
                {
                    Debug.LogError($"字符串匹配错误: Match:{match} Index:{match.Index} Open:{openIdx} Close:{closeIdx}");
                    continue;
                }
                var json = text.Substring(openIdx, closeIdx - openIdx + 1);
                var jsonPath = $"{PathDefine.DefaultOutputPath}/{match.Value}";
                var jsonDir = Path.GetDirectoryName(jsonPath);
                if (!Directory.Exists(jsonDir))
                {
                    Directory.CreateDirectory(jsonDir);
                }
                File.WriteAllText(jsonPath, json);
            }
        }
        /// <summary>
        /// 反向查找指定字符的索引
        /// </summary>
        /// <param name="text"></param>
        /// <param name="char"></param>
        /// <param name="startIndex">小于零或者大于字符串长度，则从字符串最后一个字符开始查找</param>
        /// <returns></returns>
        private static int IndexOfReverse(this string text, char @char, int startIndex = -1)
        {
            if (startIndex < 0 || startIndex > text.Length - 1)
            {
                startIndex = text.Length - 1;
            }
            for(var index = startIndex; index >= 0; index--)
            {
                if (@char == text[index])
                {
                    return index;
                }
            }
            return -1;
        }
    }
}
