#if UNITY_ANDROID
namespace Guru
{
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using UnityEditor;
    using UnityEditor.Build;
    using UnityEditor.Build.Reporting;
    using UnityEngine;
    
    /// <summary>
    /// Android混淆器内容填充
    /// 于应用构建前执行
    /// </summary>
    public class UserProguardHelper: IPreprocessBuildWithReport
    {
        public int callbackOrder { get; } = 0;
        public void OnPreprocessBuild(BuildReport report)
        {
            // 修复ProguardFile
            OnApplyProguardFiles();
        }
        
        private static void OnApplyProguardFiles()
        {
            string proguardPath = $"{Application.dataPath}/Plugins/Android/proguard-user.txt";
            if (File.Exists(proguardPath))
            {
                List<string> keeps = new List<string>();
                DirectoryInfo dir = new DirectoryInfo(Application.dataPath);
                string raw = File.ReadAllText(proguardPath);
                
                if (dir.Exists)
                {
                    var editors = dir.GetDirectories("Editor", SearchOption.AllDirectories);
                    List<FileInfo> files = new List<FileInfo>();
                    foreach (var e in editors)
                    {
                        files.AddRange(e.GetFiles("*Proguards.txt", SearchOption.AllDirectories));
                    }
                    
                    // Debug.Log($"--- Proguard Files: {files.Length}");

                    string[] lens = null;
                    string l = "";
                    for (int i = 0; i < files.Count; i++)
                    {
                        lens = File.ReadAllLines(files[i].FullName);
                        foreach (var s in lens)
                        {
                            l = s.TrimStart();
                            if(string.IsNullOrEmpty(l)) continue;
                            if(raw.Contains(l)) continue;
                            keeps.Add(l);
                            Debug.Log($"--- ✏️ Apply: [ {l} ]");
                        }
                    }
                }
                
                if (keeps.Count == 0) return; // 无注入文件则退出
                
                List<string> lines = File.ReadAllLines(proguardPath).ToList();
                lines.Add("");
                lines.AddRange(keeps);
                
                File.WriteAllLines(proguardPath, lines.ToArray());
                Debug.Log($"--- Update proguard-user.txt done! ☀️ ---");
                
            }
        }
        
        
        [MenuItem("Tools/Android/Add proguard-user")]
        private static void EditorAddProguardUser()
        {
            OnApplyProguardFiles();
        }

    }
}

#endif