// WPFMA-SDK needs Unity 2022.3 (VRChat's version); on older Unity this file is skipped and WPFMAUnityVersionNotice explains why.
#if UNITY_2022_3_OR_NEWER
using System;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;

namespace WPFMA
{
    internal static class WPFMAQuestSwitchHost
    {
        private const string WindowTypeName = "EasyQuestSwitch.EQS_Window";
        private const string PackagePath = "Packages/vrchat.jordo.easyquestswitch";

        private static Type windowType;
        private static bool typeResolved;

        private static EditorWindow hosted;
        private static MethodInfo onGui;

        private static string hostFailure;

        internal static bool IsInstalled
        {
            get { return ResolveType() != null; }
        }

        internal static string Failure
        {
            get { return hostFailure; }
        }

        internal static bool Draw()
        {
            if (hostFailure != null)
                return false;

            var type = ResolveType();
            if (type == null)
                return false;

            try
            {
                if (hosted == null)
                {
                    hosted = (EditorWindow)ScriptableObject.CreateInstance(type);
                    hosted.hideFlags = HideFlags.HideAndDontSave;
                    onGui = null;
                }

                if (onGui == null)
                {
                    onGui = type.GetMethod("OnGUI", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                    if (onGui == null)
                    {
                        hostFailure = "EasyQuestSwitch changed shape and its interface could not be embedded.";
                        return false;
                    }
                }

                onGui.Invoke(hosted, null);
                return true;
            }
            catch (Exception e)
            {
                var cause = e is TargetInvocationException && e.InnerException != null ? e.InnerException : e;

                if (cause is ExitGUIException)
                    throw cause;

                hostFailure = cause.Message;
                Debug.LogWarning("[WPFMA-SDK] Could not embed EasyQuestSwitch, falling back to its own window: " + cause);
                Release();
                return false;
            }
        }

        internal static void Release()
        {
            if (hosted != null)
                UnityEngine.Object.DestroyImmediate(hosted);

            hosted = null;
            onGui = null;
        }

        internal static void Reset()
        {
            Release();
            hostFailure = null;
            typeResolved = false;
            windowType = null;
        }

        private static Type ResolveType()
        {
            if (typeResolved)
                return windowType;

            typeResolved = true;
            windowType = null;

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                try
                {
                    var found = assembly.GetType(WindowTypeName, false);
                    if (found != null)
                    {
                        windowType = found;
                        break;
                    }
                }
                catch (Exception)
                {
                }
            }

            return windowType;
        }

        internal static bool IsPendingImport()
        {
            return ResolveType() == null && System.IO.Directory.Exists(PackagePath);
        }
    }
}
#endif
