using System.Collections.Generic;
using UnityEngine;

namespace XGame.Framework.Memory
{
    public delegate void CleanMemoryDelegate();

    /// <summary>
    /// 内存监控，业务不要用
    /// </summary>
    public static class MemoryMonitor
    {
        private static HashSet<CleanMemoryDelegate> _delegateRegisters = new HashSet<CleanMemoryDelegate>();

        static MemoryMonitor()
        {
            Application.lowMemory += OnLowMemory;
        }

        private static void OnLowMemory()
        {
            Log.Info("内存警告!!");
            CleanMemory();
        }

        public static void CleanMemory()
        {
            Log.Info("Clean Memory!!");

            foreach (var register in _delegateRegisters)
            {
                try
                {
                    register?.Invoke();
                }
                catch (System.Exception e)
                {
                    Log.Error($"Memory Warning Delegate Exception: Message: {e.Message}, StackTrace: {e.StackTrace}");
                }
            }
            //TODO 
            //AssetHelper.UnloadUnusedAssets();
            System.GC.Collect();
            Log.Info("Clean Memory Done...");
        }

        public static void Register(CleanMemoryDelegate register)
        {
            if (register == null)
                return;

            if (!_delegateRegisters.Contains(register))
                _delegateRegisters.Add(register);
        }


        public static void UnRegister(CleanMemoryDelegate unRegister)
        {
            if (unRegister == null)
                return;

            if (_delegateRegisters.Contains(unRegister))
                _delegateRegisters.Remove(unRegister);
        }

        internal static void Dispose()
        {
            _delegateRegisters.Clear();
        }
    }
}
