using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AspNetCore.HealthChecks.Memory
{
    public class MemoryHealthCheck : IHealthCheck
    {
        private readonly IOptionsMonitor<MemoryCheckOptions> _options;

        public MemoryHealthCheck(IOptionsMonitor<MemoryCheckOptions> options)
        {
            _options = options;
        }

        public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = _options.Get(context.Registration.Name);

            var allocated = GC.GetTotalMemory(forceFullCollection: false);

            var data = new Dictionary<string, object>()
            {
                { "AllocatedBytes",allocated},
                { "Gen0Collections",GC.CollectionCount(0)},
                { "Gen1Collections",GC.CollectionCount(1)},
                { "Gen2Collections",GC.CollectionCount(2)},
            };

            var stuats = allocated < options.Threshold ? HealthStatus.Healthy : HealthStatus.Unhealthy;

            return Task.FromResult(new HealthCheckResult(stuats, "Reports degraded status if allocated bytes", null, data));
        }
    }
}
