using System;
using System.Threading.Tasks;
using GxPress.Api.Tools;
using GxPress.Service.Interface.ElasticSearch;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Quartz;

namespace GxPress.Api.AdminControllers
{
    [Route("api/admin/job")]
    [ApiController]
    [Authorize]
    public class AdminJobController : ControllerBase
    {
        private readonly ISchedulerFactory _schedulerFactory;

        private readonly IServiceProvider _serviceProvider;
        private IScheduler _scheduler;
        private readonly IElasticSearchService _elasticSearchService;
        public AdminJobController(ISchedulerFactory schedulerFactory, IElasticSearchService elasticSearchService, IServiceProvider serviceProvider)
        {
            this._schedulerFactory = schedulerFactory;
            _elasticSearchService = elasticSearchService;
            _serviceProvider = serviceProvider;
        }
        [HttpGet]
        [AllowAnonymous]
        public async Task<bool> Get()
        {
            //1、通过调度工厂获得调度器
            _scheduler = await _schedulerFactory.GetScheduler();
            //2、开启调度器
            await _scheduler.Start();
            //3、创建一个触发器
            var trigger = TriggerBuilder.Create()
                            .WithSimpleSchedule(x => x.WithIntervalInSeconds(60).RepeatForever())//每10秒执行一次
                            .Build();
            //构建工厂 构造函数
            _scheduler.JobFactory = new JobFactory(_serviceProvider, _elasticSearchService);
            // await _scheduler.ScheduleJob(trigger);
            //4、创建任务
            var jobDetail = JobBuilder.Create<MyJob>()
                            .WithIdentity("job1", "group1")
                            .Build();
            //5、将触发器和任务器绑定到调度器中
            await _scheduler.ScheduleJob(jobDetail, trigger);
            //await _scheduler.Start();
            //await _scheduler.Shutdown();
            return true;
        }
    }
}