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
    {
        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)
        {
            _scheduler.Start(cancellationToken);
            // 此种方法创建任务，可用构造函数，注入对象 
            var jobBuilderType = typeof(JobBuilder);
            var method = jobBuilderType.GetMethods().FirstOrDefault(
                    x => x.Name.Equals("Create", StringComparison.OrdinalIgnoreCase) &&
                         x.IsGenericMethod && x.GetParameters().Length == 0)
                ?.MakeGenericMethod(typeof(GlobalSubscribe));

            var jobBuilder = (JobBuilder)method.Invoke(null, null);

            IJobDetail jobDetail = jobBuilder.WithIdentity("GlobalSubscribe").Build();
            var trigger = TriggerBuilder.Create()
                .WithIdentity("SubscribeJobTrigger", "GlobalSubscribe")
                .WithSimpleSchedule(x => { x.WithIntervalInSeconds(30).RepeatForever(); })
                .Build();


            //todo 临时注销
            //_scheduler.ScheduleJob(jobDetail, trigger, cancellationToken);

            var method1 = jobBuilderType.GetMethods().FirstOrDefault(
                    x => x.Name.Equals("Create", StringComparison.OrdinalIgnoreCase) &&
                         x.IsGenericMethod && x.GetParameters().Length == 0)
                ?.MakeGenericMethod(typeof(ConfigSubscribe));

            var jobBuilder1 = (JobBuilder)method1.Invoke(null, null);

            IJobDetail jobDetail1 = jobBuilder1.WithIdentity("ConfigSubscribe").Build();
            var bootTrigger = TriggerBuilder.Create()
                .WithIdentity("bootTrigger")
                .StartNow()
                .WithSimpleSchedule(x => x.WithRepeatCount(0)).Build();
            _scheduler.ScheduleJob(jobDetail1, bootTrigger, cancellationToken);

            /*var map = new JobDataMap();
            map.Put("redisCacheContext", _serviceProvider.GetService<ICacheContext>());
            map.Put("ServiceProvider", _serviceProvider);
            var job = JobBuilder.Create<GlobalSubscribe>().UsingJobData(map)
                .WithIdentity("subscribe", "GlobalSubscribe").Build();
            //创建一个触发条件
            var trigger = TriggerBuilder.Create()
                .WithIdentity("SubscribeJobTrigger", "GlobalSubscribe")
                .WithSimpleSchedule(x => { x.WithIntervalInSeconds(30).RepeatForever(); })
                .Build();
            var onceTrigger = TriggerBuilder.Create()
                .WithIdentity("onceTrigger")
                .WithSimpleSchedule(x => x.WithRepeatCount(0)).Build();

            _scheduler.ScheduleJob(job, trigger, 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()
        {
        }
    }
}