using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Runtime.CompilerServices;

namespace InABox.Core
{
    
    public class EventSuppressor : IDisposable
    {
        private static Dictionary<Enum, int> _cache = new Dictionary<Enum, int>();

        private Enum[] _scopes;

        public static ImmutableDictionary<Enum, int> Cache() => _cache.ToImmutableDictionary();
        
        public EventSuppressor(params Enum[] scopes)
        {
            _scopes = scopes;
            foreach (var scope in scopes)
            {
                _cache.TryGetValue(scope, out int count);
                _cache[scope] = count + 1;
            }
        }
        
        public void Dispose()
        {
            foreach (var scope in _scopes)
            {
                if (_cache.TryGetValue(scope, out int count))
                {
                    if (count <= 1)
                        _cache.Remove(scope);
                    else
                        _cache[scope] = count - 1;
                }
            }
        }

        public static bool IsSet(Enum scope) => _cache.TryGetValue(scope, out int count) && (count > 0);

        public static EventSuppressor All<T>() where T : Enum
        {
            var scopes = Enum.GetValues(typeof(T)).Cast<Enum>().ToArray();
            return new EventSuppressor(scopes);
        }
        
    }
}