using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
using UnityEditor;
using System.Text.RegularExpressions;
using System.Linq;

namespace EditorUtils
{
 
    public class JsonToLua 
    {

        static string GetIndent(int indentNum)
        {
            return RepeatString("\t", indentNum);
        }
        static string RepeatString(string input, int times)
        {
            //Debug.Log(times);
            return string.Concat(Enumerable.Repeat(input, times));
        }
        public static void ConvertFile(string jsonFile,string luaFile)
        {
            string jsonText = File.ReadAllText(jsonFile);
            JToken token = JToken.Parse(jsonText);
            string luaContent = "return ";
            int indentNum = -1;
           if (token is JObject) {
                JObject jsonObject = JObject.Parse(jsonText);
                luaContent += ProcessObject(jsonObject,indentNum);
            }
            else if(token is JArray)
            {
                JArray jsonArray = JArray.Parse(jsonText);
                luaContent += ProcessArray(jsonArray,indentNum);
            }

            luaContent += "\n return config";
            File.WriteAllText(luaFile, luaContent);

            AssetDatabase.Refresh();
            Debug.Log("Conversion complete.");
        }

        public static string ConvertContent(string jsonText)
        {
            JToken token = JToken.Parse(jsonText);
            string luaContent = "return ";
            int indentNum = -1;
            if (token is JObject)
            {
                JObject jsonObject = JObject.Parse(jsonText);
                luaContent += ProcessObject(jsonObject, indentNum);
            }
            else if (token is JArray)
            {
                JArray jsonArray = JArray.Parse(jsonText);
                luaContent += ProcessArray(jsonArray, indentNum);
            }

            return luaContent;
        }

        // 递归处理 JSON 对象
        static string ProcessObject(JObject obj,int indentNum)
        {
            indentNum += 1;
            string luaContent = "\n" + GetIndent(indentNum) + "{\n";
            indentNum += 1;
            var propertys = obj.Properties().OrderBy(p => p.Name);// 按照键排序
            foreach (var property in propertys)
            {
                string key = property.Name;
                JToken value = property.Value;
                luaContent += GetIndent(indentNum);
                //luaContent +=  Regex.IsMatch(key, @"^\d+$") ? $"[{key}] = " : Regex.IsMatch(key,@"[\u4e00-\u9fa5]+") ? $"[\"{key}\"] = " : $"{key} =  ";
                luaContent +=  $"[\"{key}\"] = ";

                if (value.Type == JTokenType.Object)
                {
                    luaContent += ProcessObject((JObject)value,indentNum);
                }
                else if (value.Type == JTokenType.Array)
                {
                    luaContent += ProcessArray((JArray)value,indentNum);
                }
                else
                {
                    luaContent += ProcessValue(value);
                }
                luaContent += ",\n";
            }
            indentNum -= 1;
            luaContent += GetIndent(indentNum) +  "}" ;
            return luaContent;
        }

        // 处理 JSON 数组
        static string ProcessArray(JArray array,int indentNum)
        {
            indentNum += 1;
            string luaContent =  "\n" + GetIndent(indentNum) + "{ \n";
            indentNum += 1;

            for (int i = 0; i < array.Count; i++)
            {
                JToken value = array[i];
                luaContent += GetIndent(indentNum);
                if (value.Type == JTokenType.Object)
                {
                    luaContent += ProcessObject((JObject)value, indentNum);
                }
                else if (value.Type == JTokenType.Array)
                {
                    luaContent += ProcessArray((JArray)value, indentNum);
                }
                else
                {
                    luaContent += ProcessValue(value);
                }

                if (i < array.Count - 1)
                {
                    luaContent += ",\n ";
                }
            }
            indentNum -= 1;
            luaContent +="\n" +  GetIndent(indentNum) + "}";
            return luaContent;
        }

        // 处理 JSON 值
        static string ProcessValue(JToken value)
        {
            string str;
            if (value.Type == JTokenType.String)
            {
                if(value.ToString().Contains('"'))
                {
                    value = value.ToString().Replace("\"", "\\\"");
                }
                str = $"\"{value}\"";
            }
            else if (value.Type == JTokenType.Null)
            {
                str = "nil";
            }
            else if (value.Type == JTokenType.Boolean)
            { 
                str = value.ToString().ToLower();
            }
            else if (value.Type == JTokenType.Integer || value.Type == JTokenType.Float)
            { 
                str = value.ToString();
            }
            else
            {
                str = $"\"{value.ToString()}\"";
            }
            return $"{str}";
        }
    }
}
