using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEditor.PackageManager;
using UnityEditor.PackageManager.Requests;
using UnityEngine;
using System.Collections.Generic;
using System.Linq;

[InitializeOnLoad]
public class XRPackageInstaller : Editor
{
    static XRPackageInstaller()
    {
        Debug.Log("Installing XR packages.");

        if (InstallPackages())
        {
            // Only set the XR_INSTALLED directive if packages were successfully installed
            //AddDefineSymbol("XR_INSTALLED", BuildTargetGroup.Standalone);
            //AddDefineSymbol("XR_INSTALLED", BuildTargetGroup.Android);
            // Repeat for other relevant build targets as necessary

            Debug.Log("XR packages installed.");

            /*EditorUtility.DisplayDialog("Restart Required",
                "Please restart Unity to complete the XR package installation.",
                "OK");
                */
        }
    }
    private static bool IsPackageInstalled(string packageId)
    {
        // Create a search request
        ListRequest request = Client.List();

        while (!request.IsCompleted)
        {
            // Wait for the request to complete
        }

        // Check if the package is found in the search results
        // Check if the desired package is in the list
        if (request.Status == StatusCode.Success && request.Result != null)
        {
            foreach (var package in request.Result)
            {
                if (package.name == packageId)
                {
                    Debug.Log($"{packageId} is installed.");
                    return true;
                }
            }
            return false;
        }
        return false;
    }

    [InitializeOnLoadMethod]
    public static bool InstallPackages()
    {
        // Check if the packages have already been installed
        if (IsPackageInstalled("com.unity.xr.management"))
        {
            Debug.Log("XR manager is already installed.");
            return true;

        }
        if (IsPackageInstalled("com.unity.xr.openxr"))
        {
            Debug.Log("XR openxr is already installed.");
            return true;

        }
        if (IsPackageInstalled("com.unity.xr.oculus"))
        {
            Debug.Log("XR oculus is already installed.");
            return true;

        }


     /*   if (EditorPrefs.GetBool("XRPackagesInstalled", false))
        {
            Debug.Log("XR packages are already installed.");
            return true;
        }
*/
        // Define the packages to install
        string[] packages = new string[]
        {
            "com.unity.xr.management",
            "com.unity.xr.openxr",
            "com.unity.xr.oculus"
        };

        // Create a request to list all installed packages
        ListRequest listRequest = Client.List();

        // Wait for the request to complete
        while (!listRequest.IsCompleted)
        {
            // Wait for the request to complete
        }

        // Get the list of installed packages
        var installedPackages = listRequest.Result;

        // Check if the packages are already installed
        if (installedPackages.Any(p => packages.Contains(p.name)))
        {
            Debug.Log("All XR packages are already installed.");
            EditorPrefs.SetBool("XRPackagesInstalled", true);
            return true;
        }

        // Loop through the packages and install them
        foreach (string packageName in packages)
        {
            // Create a request to add the package
            AddRequest request = Client.Add(packageName);

            // Wait for the request to complete
            while (!request.IsCompleted)
            {
                // Wait for the request to complete
            }

            // Check if the package installation was successful
            if (request.Status == StatusCode.Success)
            {
                Debug.Log($"{packageName} installed successfully!");
            }
            else
            {
                Debug.LogError($"Failed to install {packageName}. Error: {request.Error.message}");
            }
        }

        // Set a flag indicating that the packages have been installed
        EditorPrefs.SetBool("XRPackagesInstalled", true);
        AddDefineSymbol("XR_INSTALLED", BuildTargetGroup.Standalone);
        AddDefineSymbol("XR_INSTALLED", BuildTargetGroup.Android);

        return true;
    }

    private static void AddDefineSymbol(string define, BuildTargetGroup targetGroup)
    {
        var definesString = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup);
        var allDefines = definesString.Split(';').ToList();
        if (!allDefines.Contains(define))
        {
            allDefines.Add(define);
            PlayerSettings.SetScriptingDefineSymbolsForGroup(
                targetGroup,
                string.Join(";", allDefines.ToArray()));
        }
    }
}
