package org.sky.scientific.excel.annotation;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.sky.core.tool.utils.StringUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class DateFormatValidator implements ConstraintValidator<ValidDateFormat, String> {

	private String pattern;
	private boolean nullable;

	@Override
	public void initialize(ValidDateFormat constraintAnnotation) {
		this.pattern = constraintAnnotation.pattern();
		this.nullable = constraintAnnotation.nullable();
	}

	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		// 如果允许为空且值为空，则直接返回true
		if (nullable && StringUtil.isBlank(value)) {
			return true;
		}

		// 如果不允许为空且值为空，返回false
		if (!nullable && StringUtil.isBlank(value)) {
			return false;
		}

		// 验证日期格式
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(pattern);
			sdf.setLenient(false); // 严格模式
			sdf.parse(value);
			return true;
		} catch (ParseException e) {
			return false;
		}
	}

}
