#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using UnityEngine.Rendering;
using System.Linq;

namespace ModestTree
{
    public class ExportProjectConfig
    {
        const string MANUAL_SETUP_INSTRUCTIONS = "Please manually enable the following settings:\n- Project Settings > XR Plug-in Management > Android > OpenXR\n- Project Settings > XR Plug-in Management > Android > OpenXR > Meta Quest Support\n\nPlease verify the following setting:\n- Project Settings > XR Plug-in Management > Android > OpenXR > Render Mode is Single Pass Instanced \\ Multi-view";
        const int PACKAGE_POLL_DELAY = 100;

        [MenuItem("ModestTree/Project Configuration - Oculus Quest")]
        public static void OculusQuestConfigureProject()
        {
            try
            {
                SetGraphicsApiToVulkan();

                Debug.Log("=== Installing Required Packages for OpenXR Setup ===");

                var packagesToInstall = new string[]
                {
                    "com.unity.xr.management",
                    "com.unity.xr.openxr"
                };

                foreach (var packageId in packagesToInstall)
                {
                    if (!IsPackageInstalled(packageId))
                    {
                        Debug.Log($"Installing package: {packageId}");
                        InstallPackage(packageId);
                    }
                    else
                    {
                        Debug.Log($"Package already installed: {packageId}");
                    }
                }

                Debug.Log("All required packages installed.");

                Debug.Log(MANUAL_SETUP_INSTRUCTIONS);
                EditorUtility.DisplayDialog(
                    "Meta Quest Configuration",
                    MANUAL_SETUP_INSTRUCTIONS,
                    "OK");

            }
            catch (System.Exception ex)
            {
                Debug.LogError($"Error installing required packages: {ex.Message}");
                Debug.LogException(ex);
            }
        }

        public static void SetGraphicsApiToVulkan()
        {
            PlayerSettings.SetUseDefaultGraphicsAPIs(BuildTarget.Android, false);

            GraphicsDeviceType[] apis = { GraphicsDeviceType.Vulkan };
            PlayerSettings.SetGraphicsAPIs(BuildTarget.Android, apis);

            AssetDatabase.SaveAssets();

            Debug.Log("Android Graphics API set to Vulkan and changes saved to project");
        }

        public static void SetGraphicsApiToOpenGLES3()
        {
            PlayerSettings.SetUseDefaultGraphicsAPIs(BuildTarget.Android, false);

            GraphicsDeviceType[] apis = { GraphicsDeviceType.OpenGLES3 };
            PlayerSettings.SetGraphicsAPIs(BuildTarget.Android, apis);

            AssetDatabase.SaveAssets();

            Debug.Log("Android Graphics API set to OpenGLES3 and changes saved to project");
        }

        static bool IsPackageInstalled(string packageId)
        {
            var request = UnityEditor.PackageManager.Client.List(true);
            while (!request.IsCompleted)
            {
                System.Threading.Thread.Sleep(PACKAGE_POLL_DELAY);
            }

            return request.Result.Any(package => package.name == packageId);
        }

        static void InstallPackage(string packageId)
        {
            var request = UnityEditor.PackageManager.Client.Add(packageId);
            while (!request.IsCompleted)
            {
                System.Threading.Thread.Sleep(PACKAGE_POLL_DELAY);
            }

            if (request.Status == UnityEditor.PackageManager.StatusCode.Success)
            {
                Debug.Log($"Package {packageId} installed successfully");
            }
            else
            {
                Debug.LogError($"Failed to install package {packageId}: {request.Error.message}");
            }
        }
    }
}
#endif
