using UnityEngine;

/// <summary>
/// Be aware this will not prevent a non singleton constructor
///   such as `T myT = new T();`
/// To prevent that, add `protected T () {}` to your singleton class.
/// 
/// As a note, this is made as MonoBehaviour because we need Coroutines.
/// </summary>
public class BaseManager<T> : MonoBehaviour where T : MonoBehaviour
{
    protected static T m_instance;
    protected static GameObject m_GameObject;

    public static T Instance
    {
        get
        {
            if (applicationIsQuitting)
            {
                Debug.LogWarning("[Manager] Instance '" + typeof(T) +
                    "' already destroyed on application quit." +
                    " Won't create again - returning null.");
                return null;
            }

            if (m_instance == null)
            {
                m_instance = (T)FindObjectOfType(typeof(T));

                if (FindObjectsOfType(typeof(T)).Length > 1)
                {
                    Debug.LogError("[Manager] Something went really wrong " +
                        " - there should never be more than 1 singleton!" +
                        " Reopening the scene might fix it.");
                    return m_instance;
                }

                if (m_instance == null)
                {
                    m_GameObject = new GameObject();
                    m_instance = m_GameObject.AddComponent<T>();
                    m_GameObject.name = "(Manager) " + typeof(T).ToString();

                    DontDestroyOnLoad(m_GameObject);

                    Debug.Log("[Manager] An instance of " + typeof(T) +
                        " is needed in the scene, so '" + m_GameObject +
                        "' was created with DontDestroyOnLoad.");
                }
                else
                {
                    Debug.Log("[Manager] Using instance already created: " +
                        m_instance.gameObject.name);
                }
            }

            return m_instance;
        }
    }

    private static bool applicationIsQuitting = false;
    /// <summary>
    /// When Unity quits, it destroys objects in a random order.
    /// In principle, a Singleton is only destroyed when application quits.
    /// If any script calls Instance after it have been destroyed, 
    ///   it will create a buggy ghost object that will stay on the Editor scene
    ///   even after stopping playing the Application. Really bad!
    /// So, this was made to be sure we're not creating that buggy ghost object.
    /// </summary>
    public void OnDestroy()
    {
        applicationIsQuitting = true;
    }

    public static bool DoesInstanceExist()
    {
        return Instance != null;
    }
}