using System;
using UnityEngine;

[AddComponentMenu("")]
public partial class CrashSightMonoBehaviour : MonoBehaviour
{
    private static CrashSightMonoBehaviour _instance;
    public static CrashSightMonoBehaviour Instance
    {
        get
        {
            if (_instance == null)
            {
                var gameObject = new GameObject("CrashSightMonoBehaviour") { hideFlags = HideFlags.HideAndDontSave };
                DontDestroyOnLoad(gameObject);
                _instance = gameObject.AddComponent<CrashSightMonoBehaviour>();
            }

            return _instance;
        }
    }

    public event Action ApplicationResuming;
    
    public event Action ApplicationPausing;

    public event Action ApplicationQuitting;

    internal bool _isRunning = true;
    
    public void UpdatePauseStatus(bool paused)
    {
        if (paused && _isRunning)
        {
            _isRunning = false;
            ApplicationPausing?.Invoke();
        }
        else if (!paused && !_isRunning)
        {
            _isRunning = true;
            ApplicationResuming?.Invoke();
        }
    }
    
    internal void OnApplicationPause(bool pauseStatus) => UpdatePauseStatus(pauseStatus);
    
    internal void OnApplicationFocus(bool hasFocus) => UpdatePauseStatus(!hasFocus);

    private void OnApplicationQuit()
    {
        ApplicationQuitting?.Invoke();
        Destroy(gameObject);
    }

    private void Awake()
    {
        DontDestroyOnLoad(gameObject);
    }
}
