using System;
using System.Reflection;
using UnityEngine;

namespace Stary.Evo
{
    public class Singleton<T> where T : class
    {
        public static T Instance
        {
            get
            {
                if (mInstance == null)
                {
                    // 通过反射获取构造
                    var ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
                    // 获取无参非 public 的构造
                    var ctor = Array.Find(ctors, c => c.GetParameters().Length == 0);

                    if (ctor == null)
                    {
                        throw new Exception("Non-Public Constructor() not found in " + typeof(T));
                    }

                    mInstance = ctor.Invoke(null) as T;
                }

                return mInstance;
            }
        }

        private static T mInstance;
    }
    /// <summary>
    /// 单例基类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class MonoSingleton<T>: MonoBehaviour where T: MonoBehaviour
    {
        private static T mInstance;

        public static T Instance
        {
            get {
                if (mInstance == null)
                {
                    T t = GameObject.FindObjectOfType<T>();
                    if (t)
                    {
                        mInstance = t;
                    }
                    else
                    {
                        GameObject go = new GameObject(typeof(T).Name);
                        mInstance = go.AddComponent<T>();
                    }

                    return mInstance;
                }

                return mInstance;
            }
        }
    

    }
    
    
    public class DoNotDestroy : MonoBehaviour
    {
        public static DoNotDestroy Instance;

        private void Awake()
        {
            if (Instance != null)
            {
                Destroy(gameObject);
                return;
            }

            Instance = this;
            DontDestroyOnLoad(gameObject);
        }      
    }
}