/*
 *Copyright(C) 2023 by Chief All rights reserved.
 *Unity版本：2023.2.5f1c1 
 *作者:Chief  
 *创建日期: 2024-01-19 
 *模块说明：通用单例模块
 *版本: 1.0
*/

using System.Collections;
using UnityEngine;

namespace Aster
{
    /// <summary>
    /// 限制单例；
    /// 由 LimitSingletonManager 管理，不是Mono类；
    /// </summary>
    public class LimitSingleton<T> where T : LimitSingleton<T>, I_AsterObject, new()
    {

        public LimitSingleton() { }

        public static T Instance { get; protected set; }


        public static T Get
        {
            get
            {
                if (Instance == null)
                {
                    Logger.LogError($"单例： {typeof(T).ToString()} 还没有创建！");
                }
                return Instance;
            }
        }

        public static bool Exist => Instance != null;

        public static T Create()
        {
            if (Instance != null)
                return Instance;

            if (!LimitSingletonManager.Exist)
            {
                Logger.LogError($"没有管理器：  LimitSingletonManager , 不能创建 ！ ");
                return null;
            }
            //在管理器中找相同的；
            Instance = LimitSingletonManager.Get.FindLimitSigleton<T>();

            //此时管理器中没有，则创建一个新的；
            if (Instance == null)
            {
                Instance = new T();
                Instance?.Start();
                LimitSingletonManager.Get.AddLimitSingleton(Instance);
            }

            return Instance;
        }

        public static void Release()
        {
            if (Instance == null)
                return;

            LimitSingletonManager.Get.RemoveLimitSingleton(Instance);
            Instance.Destroy();
            Instance = null;
        }

        public virtual void Start() { }

        public virtual void Update() { }

        public virtual void LateUpdate() { }

        public virtual void Destroy() { }

        public Coroutine StartCoroutine(IEnumerator routine) { return LimitSingletonManager.Get.StartCoroutine(routine); }

        public void StopCoroutine(Coroutine routine) { LimitSingletonManager.Get.StopCoroutine(routine); }

    }
}