using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System;
using System.Text;

public class GenTestSections
{
    public static string AssetsRoot = Application.dataPath.Replace("\\", "/") + "/"; //F:/repos/ihuman-art/app/Assets/

    [MenuItem("Tool/Game.GenTestSectionIds", false)]
    [Tooltip("生成 TestSectionIds.lua 测试")]
    public static void GenAllSections()
    {
        string destFile = AssetsRoot + "app/src/scenes/game/TestSectionIds.lua";
        // var registerFiles = Directory.GetFiles(AssetsRoot + "gamesrc", "*register.lua", SearchOption.AllDirectories);
        //遍历 files, 把内容拼接起来，生成 destFile
        string destDir = Path.GetDirectoryName(destFile);
        if (!Directory.Exists(destDir))
        {
            Directory.CreateDirectory(destDir);
        }

        Dictionary<string, List<string>> result = new Dictionary<string, List<string>>();
        result["book"] = GenOneSection(AssetsRoot + "art/book");
        result["expand"] = GenOneSection(AssetsRoot + "art/game/expand");
        result["say"] = GenOneSection(AssetsRoot + "art/game/say");
        result["practice"] = GenOneSection(AssetsRoot + "art/game/practice");
        result["weekly"] = GenOneSection(AssetsRoot + "art/game/weekly");
        result["poetry"] = GenOneSection(AssetsRoot + "gamesrc/poetry/poetries");
        result["monthly"] = GenOneSection(AssetsRoot + "art/game/monthly");

        WriteToLuaFile(result, destFile);
        Debug.Log("GenTestSectionIds.GenAllSections Suc");
    }

    public static List<string> GenOneSection(string folderPath)
    {
        try
        {
            List<string> tmp = new List<string>();
            // 获取文件夹中的所有子文件夹  
            string[] subfolders = Directory.GetDirectories(folderPath);
            foreach (string subfolder in subfolders)
            {
                string folderName = Path.GetFileName(subfolder);
                Match match = Regex.Match(folderName, @"\d+"); // 匹配一个或多个数字  
                if (match.Success)
                {
                    // 将数字部分转换为字符串并存放到字典中  
                    tmp.Add(match.Value);
                }
            }
            return tmp;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
            return null; // 或者返回一个空的字典，根据需要选择合适的返回值  
        }
    }

    public static void WriteToLuaFile(Dictionary<string, List<string>> dictionary, string filePath)  
    {
        StringBuilder luaCode = new StringBuilder();
        luaCode.AppendLine("--本文件通过 Tool->game.GenTestSectionIds 自动生成，请勿手动修改。");
        luaCode.AppendLine("defGlobal(\"TestSectionIds\")");
        luaCode.AppendLine("TestSectionIds = {");
        int oneLineChars = 115;
        foreach (var entry in dictionary)
        {
            //luaCode.AppendLine($"\t{entry.Key} = {StringifyList(entry.Value)},");

            luaCode.AppendLine($"\t{entry.Key} = {{");
            string value = StringifyList(entry.Value);
            value = value.Substring(1, value.Length-2);
            while(value.Length > oneLineChars && value.IndexOf(",", oneLineChars) != -1)
            {
                int index = value.IndexOf(",", oneLineChars);
                string oneline = value.Substring(0, index+1);
                value = value.Substring(index+2);
                luaCode.AppendLine($"\t\t{oneline}");
            }
            luaCode.AppendLine($"\t\t{value}");
            luaCode.AppendLine($"\t}},");
        }
        luaCode.AppendLine("}");


        File.WriteAllText(filePath, luaCode.ToString());  
    }  

    private static string StringifyList(List<string> list)  
    {  
        if (list == null || list.Count == 0)  
            return "{}"; // 返回一个空列表的字符串表示形式  
  
        StringBuilder sb = new StringBuilder("{");  
        bool isFirst = true;
        foreach (var item in list)  
        {  
            if (isFirst)  
                isFirst = false;  
            else  
                sb.Append(", ");  
            sb.Append("\""); // 添加双引号开始字符串  
            sb.Append(item); // 添加列表中的元素值  
            sb.Append("\""); // 添加双引号结束字符串  
        }  
        sb.Append("}"); // 添加右括号结束列表的字符串表示形式  
        return sb.ToString();  
    }  
}