using System;
using System.Threading;
using System.Threading.Tasks;
using Infrastructure.Cache;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenAuth.App.BaseApp.Subscribe;
using Quartz;
using Quartz.Impl;

namespace OpenAuth.App.HostedService
{
    /// <summary>
    /// 自启动服务，本服务用于启动所有状态为【正在运行】的定时任务
    /// </summary>
    public class QuartzService : IHostedService, IDisposable, IAsyncDisposable
    {
        private readonly ILogger<QuartzService> _logger;
        private IScheduler _scheduler;
        private OpenJobApp _openJobApp;
        private IServiceProvider _serviceProvider;

        public QuartzService(ILogger<QuartzService> logger, IScheduler scheduler, OpenJobApp openJobApp,
            IServiceProvider serviceProvider)
        {
            _logger = logger;
            _scheduler = scheduler;
            _openJobApp = openJobApp;
            _serviceProvider = serviceProvider;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            var result = _openJobApp.StartAll();
            return result;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            var result = _scheduler.Shutdown();
            _logger.LogInformation("关闭定时job");
            return result;

            //return Task.CompletedTask;
        }

        public void Dispose()
        {
            _scheduler?.Shutdown().ConfigureAwait(false).GetAwaiter().GetResult();
        }
        
        public async ValueTask DisposeAsync()
        {
            if (_scheduler != null)
            {
                await _scheduler.Shutdown();
            }
        }
    }
}