using Beam.Abstractions;

namespace Beam.Models {
    /// <summary>
    /// Holds a collection of <see cref="IDocument"/> objects in memory to facilitate lazy loading
    /// </summary>
    public class DocumentCache : Dictionary<object, IDocument>, IDisposable {
        private bool disposedValue;

        /// <summary>
        /// Calculates memory usage and checks if it does not exceed a certain limit
        /// </summary>
        /// <param name="allocatedSpaceInBytes">The memory limit</param>
        /// <returns></returns>
        public bool IsCapacityLessThan(int allocatedSpaceInBytes) {
            return this.Count < CalculateMemorySpaceUsage(); 
        }

        /// <summary>
        /// Gets an estimate of the space used by the IDocument objects (disregarding metadata) in bytes.
        /// </summary>
        /// <returns>Estimated memory usage in bytes</returns>
        public long CalculateMemorySpaceUsage() {
            return this.Select((x) => (x.Value.ToBytes().LongLength)).Aggregate((x, y) => x + y);
        }

        protected virtual void Dispose(bool disposing) {
            if (!disposedValue) {
                if (disposing) {
                    // TODO: dispose managed state (managed objects)
                    this.Clear();
                }

                // TODO: free unmanaged resources (unmanaged objects) and override finalizer
                // TODO: set large fields to null
                disposedValue = true;
            }
        }

        // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
        // ~DocumentCache()
        // {
        //     // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
        //     Dispose(disposing: false);
        // }

        public void Dispose() {
            // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }
    }
}
