using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using UnityEngine;
using Object = UnityEngine.Object;

namespace JohnsonUtils.Utilities
{
    public static class DontDestroyOnLoadUtils
    {
        private static readonly List<GameObject> ManagedObjects = new ();

        public static void Add(GameObject gameObject)
        {
            ManagedObjects.Add(gameObject);
            Object.DontDestroyOnLoad(gameObject);
        }

        [PublicAPI]
        public static void DestroyAll(Func<GameObject, bool> filter = null)
        {
            foreach (GameObject managedObject in ManagedObjects.ToList())
            {
                if (filter != null && !filter.Invoke(managedObject))
                    continue;
                
                Object.DestroyImmediate(managedObject);
            }
            ManagedObjects.Clear();
        }
    }
}