using Admin.Core.Common;
using Admin.Core.IService.ISys;
using Admin.Core.Model.Sys;
using Admin.Core.Tasks;
using log4net;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using StackExchange.Profiling.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Admin.Core.Extensions
{
    /// <summary>
    /// Quartz 启动服务
    /// </summary>
    public static class QuartzJobMildd
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(QuartzJobMildd));
        public static void UseQuartzJobMildd(this IApplicationBuilder app, ISysTasksQzService tasksQzService, ISchedulerCenter schedulerCenter)
        {
            if (app == null) throw new ArgumentNullException(nameof(app));

            try
            {
                if (Appsettings.app("Middleware", "QuartzNetJob", "Enabled").ObjToBool())
                {
                    var allQzServices = Appsettings.app<SysTasksQz>("QuartzNetJob").ToList(); //tasksQzService.Query(x => x.DelFlag == false);

                    foreach (var item in allQzServices)
                    {
                        if ((bool)item.IsStart)
                        {
                            var ResuleModel = schedulerCenter.AddScheduleJobAsync(item).Result;
                            if (ResuleModel.success)
                            {
                                Console.WriteLine($"QuartzNetJob{item.Name}启动成功!");
                            }
                            else
                            {
                                Console.WriteLine($"QuartzNetJob{item.Name}启动失败!错误信息:{ResuleModel.msg}");
                            }
                        }
                    }

                }
            }
            catch (Exception e)
            {
                log.Error($"An error was reported when starting the job service.\n{e.Message}");
                throw;
            }
        }
    }
}