using ConjureOS.ArcadeMenu;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

namespace ConjureOS.GlobalObject
{
#if UNITY_EDITOR
    [InitializeOnLoad]
#endif
    public static class ConjureGlobalObjectInitializer
    {
        public const string GlobalObjectName = "ConjureGlobalObject";
        public static readonly System.Type[] GlobalObjectComponentTypes =
        {
            typeof(ConjureArcadeMenu)
        };
        
#if UNITY_EDITOR
        static ConjureGlobalObjectInitializer()
        {
            InitializeGlobalObject();
        }
#endif
        
        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
        private static void InitializeGlobalObject()
        {
            GameObject globalObject = GameObject.Find(GlobalObjectName);
            if (!globalObject)
            {
                globalObject = new GameObject(GlobalObjectName);
            }
            InitializeComponentsOnGlobalObject(globalObject);
        }

        private static void InitializeComponentsOnGlobalObject(GameObject globalObject)
        {
            foreach (var globalObjectComponentType in GlobalObjectComponentTypes)
            {
                if (globalObject.GetComponent(globalObjectComponentType))
                {
                    continue;
                }
                
                if (!globalObjectComponentType.IsSubclassOf(typeof(MonoBehaviour)))
                {
                    Debug.LogError($"ConjureOS: Cannot add component '{nameof(globalObjectComponentType.FullName)}' to global object because it is not a component.");
                    continue;
                }

                globalObject.AddComponent(globalObjectComponentType);
            }
        }
    }
}