package com.lanyuanxiaoyao.service.scheduler.quartz.distribute.strategy;

import com.cronutils.model.CronType;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.eclipse.collections.api.map.ImmutableMap;

/**
 * 时间限制
 *
 * @author ZhangJiacheng
 * @date 2023-06-08
 */
public class DatetimeLimit implements AvailableStrategy {
    private static final CronParser PARSER = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ));

    private final Boolean runInPeriod;
    private final ExecutionTime execution;

    public DatetimeLimit(Boolean runInPeriod, String cron) {
        this.runInPeriod = runInPeriod;
        this.execution = ExecutionTime.forCron(PARSER.parse(cron));
    }

    @Override
    public boolean available(ImmutableMap<String, String> metadata) {
        return runInPeriod == execution.isMatch(ZonedDateTime.now().withNano(0));
    }
}
