using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace HealthCheckSample.Extensions
{
    public class StartupHostedService : IHostedService
    {
        private readonly ILogger _logger;

        private readonly StartupHostedServiceHealthCheck _startupHostedServiceHealthCheck;

        private readonly int _delaySeconds = 1;

        public StartupHostedService(ILogger<StartupHostedService> logger, StartupHostedServiceHealthCheck startupHostedServiceHealthCheck)
        {
            _logger = logger;
            _startupHostedServiceHealthCheck = startupHostedServiceHealthCheck;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation($"Startup Background Service is starting.");

            while (true)
            {
                if (DateTime.Now.Minute % 2 == 0)
                {
                    _startupHostedServiceHealthCheck.IsEvenNumber = true;
                }
                else
                {
                    _startupHostedServiceHealthCheck.IsEvenNumber = false;
                }

                Task.Delay(TimeSpan.FromSeconds(_delaySeconds)).Wait();
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Startup Background Service is stopping.");

            return Task.CompletedTask;
        }
    }
}
