using Quartz;
using Quartz.Spi;

namespace Application.Web;
public class JobStart: ITimerAutoStart
{
    private readonly ISchedulerFactory _schedulerFactory;
    private readonly IJobFactory _jobFactory;

    public JobStart(
        ISchedulerFactory schedulerFactory,
        IJobFactory jobFactory)
    {
        _schedulerFactory = schedulerFactory;
        _jobFactory = jobFactory;
    }

    public IScheduler Scheduler { get; private set; }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        Scheduler = await _schedulerFactory.GetScheduler(cancellationToken);
        Scheduler.JobFactory = _jobFactory;

        // 创建作业
        var job = JobBuilder.Create<AutoJob>()
            .WithIdentity("DayHandle", "Handle")
            .Build();

        // 创建触发器
        var trigger = TriggerBuilder.Create()
            .WithIdentity($"DayHandle_trigger", "Handle")
            .WithCronSchedule("0 0 0 * * ? ")
            .Build();

        await Scheduler.ScheduleJob(job, trigger, cancellationToken);
        await Scheduler.Start(cancellationToken);

        Console.WriteLine("----航海时代V3自动程序已启动-----");
    }

    public async Task Begin()
    {
        Scheduler = await _schedulerFactory.GetScheduler();
        Scheduler.JobFactory = _jobFactory;

        // 创建作业
        var job = JobBuilder.Create<AutoJob>()
            .WithIdentity("111", "test")
            .Build();

        // 创建触发器
        var trigger = TriggerBuilder.Create()
            .WithIdentity($"111_trigger", "test")
            .WithCronSchedule("0/1 * * * * ? ")
            .Build();

        await Scheduler.ScheduleJob(job, trigger);
        await Scheduler.Start();

        Console.WriteLine("----探玩驿站自动程序已启动-----");
    }

    public async Task StopAsync(CancellationToken cancellationToken)
    {
        await Scheduler?.Shutdown(cancellationToken);
    }
}