package com.spring.common.validation;

import java.text.ParseException;
import java.util.Date;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.quartz.CronExpression;

public class CronExpressionValidator implements ConstraintValidator<ValidCronExpression, String> {

    @Override
    public boolean isValid(String cronExpression, ConstraintValidatorContext context) {
        if (cronExpression == null || cronExpression.isEmpty()) {
            return false;
        }
        boolean result = false;
        if(CronExpression.isValidExpression(cronExpression)){
            try {
                CronExpression targetExpression = new CronExpression(cronExpression);
                if (targetExpression.getNextValidTimeAfter(new Date(System.currentTimeMillis())) != null) {
                    result = true;
                }
            } catch (ParseException e) {
                result = false;
            }
        }
        return result;
    }

}
