#if UNITY_EDITOR
using System;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace DeviantMobile.Editor.Android
{
    [InitializeOnLoad]
    internal static class AppUIActivityVibratorPatch
    {
        private const string PackageName = "com.unity.dt.app-ui";
        private const string RelativeJavaPath = "Runtime/Core/Platform/Android/Plugins/Android/AppUIActivity.java";
        private const string PackageAssetPath = "Packages/" + PackageName + "/" + RelativeJavaPath;

        static AppUIActivityVibratorPatch()
        {
            EditorApplication.update += ApplyOnceWhenEditorReady;
        }

        private static void ApplyOnceWhenEditorReady()
        {
            EditorApplication.update -= ApplyOnceWhenEditorReady;
            TryApplyPatch();
        }

        [MenuItem("Tools/Android/App UI/Reapply Vibrator Compatibility Patch")]
        private static void ReapplyPatchFromMenu()
        {
            if (TryApplyPatch(force: true))
            {
                Debug.Log("Reapplied App UI vibrator compatibility patch.");
            }
            else
            {
                Debug.LogWarning("App UI vibrator compatibility patch could not be applied. See console for details.");
            }
        }

        private static bool TryApplyPatch(bool force = false)
        {
            try
            {
                var packageInfo = UnityEditor.PackageManager.PackageInfo.FindForAssetPath("Packages/" + PackageName);
                if (packageInfo == null)
                {
                    Debug.LogWarning($"Package '{PackageName}' could not be located. Skipping App UI vibrator patch.");
                    return false;
                }

                var javaFilePath = Path.Combine(packageInfo.resolvedPath, RelativeJavaPath);
                if (!File.Exists(javaFilePath))
                {
                    Debug.LogWarning($"AppUIActivity.java not found at '{javaFilePath}'.");
                    return false;
                }

                var currentSource = File.ReadAllText(javaFilePath);
                if (!force && currentSource.Contains("Unable to access VibratorManager"))
                {
                    return true; // already patched
                }

                var templatePath = Path.Combine(Application.dataPath, "Editor/AndroidTemplates/AppUIActivity.java.txt");
                if (!File.Exists(templatePath))
                {
                    Debug.LogWarning($"Template Java source missing at '{templatePath}'.");
                    return false;
                }

                var patchedSource = File.ReadAllText(templatePath);
                File.WriteAllText(javaFilePath, patchedSource);

                AssetDatabase.ImportAsset(PackageAssetPath);
                Debug.Log("Applied App UI vibrator compatibility patch.");
                return true;
            }
            catch (Exception exception)
            {
                Debug.LogException(exception);
                return false;
            }
        }
    }
}
#endif
