#nullable enable
using AdvChkSys.Interfaces;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

namespace AdvChkSys.Resources
{
    /// <summary>
    /// Manages allocation and release of chunk resources in memory.
    /// Can be extended to track resource usage, pooling, or implement custom memory strategies.
    /// </summary>
    public static class ChunkResourceManager
    {
        // Example: Track allocated chunks (for diagnostics, pooling, or resource limits)
        private static readonly ConcurrentDictionary<IChunk, DateTime> _allocatedChunks = new();
        private static readonly object _lock = new();
        private static readonly HashSet<IChunk> _activeChunks = new();

        /// <summary>
        /// Called when a chunk is allocated/loaded into memory.
        /// Tracks the chunk and can be extended for pooling or resource limits.
        /// </summary>
        public static void AllocateChunk(IChunk chunk)
        {
            lock (_lock)
            {
                _activeChunks.Add(chunk);
                _allocatedChunks[chunk] = DateTime.UtcNow;
            }
        }

        /// <summary>
        /// Called when a chunk is released/unloaded from memory.
        /// Removes the chunk from tracking and can be extended for pooling or cleanup.
        /// </summary>
        public static void ReleaseChunk(IChunk chunk)
        {
            lock (_lock)
            {
                _activeChunks.Remove(chunk);
                _allocatedChunks.TryRemove(chunk, out _);
            }
        }

        /// <summary>
        /// Gets the current number of allocated chunks.
        /// </summary>
        public static int AllocatedChunkCount => _allocatedChunks.Count;

        /// <summary>
        /// Clears all tracked chunks (for diagnostics or shutdown).
        /// </summary>
        public static void Clear()
        {
            _allocatedChunks.Clear();
            lock (_lock)
            {
                _activeChunks.Clear();
            }
        }

        /// <summary>
        /// Gets the current count of active chunks being tracked by the resource manager.
        /// </summary>
        /// <returns>The number of active chunks</returns>
        public static int GetActiveChunkCount()
        {
            lock (_lock)
            {
                return _activeChunks.Count;
            }
        }
    }
}