using Quartz.Impl;
using Quartz;

namespace AipGateway.API.Job
{
    public class ScheduleService
    {
        private readonly ILogger<ScheduleService> _log;
        private readonly IScheduler _scheduler;
        
        public ScheduleService(ILogger<ScheduleService> logger)
        {
            _log = logger;
            _scheduler = new StdSchedulerFactory().GetScheduler().Result;
        }

        public IScheduler GetScheduler()
        {
            return _scheduler;
        }

        public void Excute<T>() where T : BaseJob, new()
        {
            var cron = new T().cron;
            _log.LogError("ScheduleService::Excute, CronExpression ==> {0}", cron);

            if (CronExpression.IsValidExpression(cron))
            {
                var job = JobBuilder.Create<T>().Build();

                var trigger = TriggerBuilder.Create().WithCronSchedule(cron).Build();

                _scheduler.ScheduleJob(job, trigger);
            }
            else
            {
                _log.LogError("ScheduleService::Excute, Invalid CronExpression ==> {0}", cron);
            }
        }

        public void Start()
        {
            _scheduler.Start();
        }
    }
}
