using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;

namespace FVS
{
    public static class FVSUnityEditorMenuGenerator
    {
        private const string GeneratedFileName = "FVSUnityEditorMenuItems.gen.cs";

        private static string GeneratedFilePath =>
            Path.Combine(Application.dataPath, "FVS-Unity/core/Editor", GeneratedFileName);

        [InitializeOnLoadMethod]
        private static void AutoGenerateOnStartup()
        {
            var currentLocale = EditorL10n.CurrentLocaleCode;
            var fileLocale = ReadGeneratedLocale();

            if (currentLocale != fileLocale)
            {
                Generate(currentLocale);
                AssetDatabase.Refresh();
            }
        }

        private static string ReadGeneratedLocale()
        {
            if (!File.Exists(GeneratedFilePath)) return null;
            var lines = File.ReadAllLines(GeneratedFilePath);
            if (lines.Length == 0) return null;
            var firstLine = lines[0];
            var prefix = "// locale:";
            if (firstLine.StartsWith(prefix))
            {
                var colonIndex = firstLine.IndexOf(':');
                return firstLine.Substring(colonIndex + 1).Trim();
            }
            return null;
        }

        private static void Generate(string locale)
        {
            var sb = new StringBuilder();
            sb.AppendLine($"// locale: {locale}");
            sb.AppendLine("// <auto-generated>");
            sb.AppendLine("// </auto-generated>");
            sb.AppendLine();
            sb.AppendLine("using UnityEditor;");
            sb.AppendLine();
            sb.AppendLine("public static class FVSUnityEditorMenuItems");
            sb.AppendLine("{");

            AppendMenuItem(sb, "Menu_CreateComponent",  "Menu_CreateComponent",    "AddFVSMain");
            AppendMenuItem(sb, "Menu_BuildSDK",        "Menu_BuildSDK",           "CreateFVSUnitySDKPackage");
            AppendMenuItem(sb, "Menu_BuildSceneConfig","Menu_BuildSceneConfig",   "CreateFVSUnityConfig");

            sb.AppendLine("}");

            var path = GeneratedFilePath;
            var dir = Path.GetDirectoryName(path);
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            File.WriteAllText(path, sb.ToString());
        }

        private static void AppendMenuItem(StringBuilder sb,
            string key, string methodName, string targetMethod)
        {
            var path = EscapeForCode(EditorL10n.Get(key));
            sb.AppendLine($"    [MenuItem(\"{path}\", false, 0)]");
            sb.AppendLine($"    public static void {methodName}()");
            sb.AppendLine("    {");
            sb.AppendLine($"        FVSUnityEditor.{targetMethod}();");
            sb.AppendLine("    }");
            sb.AppendLine();
        }

        private static string EscapeForCode(string s)
        {
            return s.Replace("\\", "\\\\").Replace("\"", "\\\"");
        }
    }
}
