package de.jottyfan.camporganizer.module.registration.validate;

import java.time.LocalDate;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;

import de.jottyfan.camporganizer.db.jooq.enums.EnumCamprole;
import de.jottyfan.camporganizer.module.registration.RegistrationRepository;

/**
 *
 * @author jotty
 *
 */
public class TeacherAgeCheckValidator implements ConstraintValidator<TeacherAgeCheck, Object> {

	private String field;
	private String fkCamp;
	private String campRole;
	private String message;

	@Autowired
	private RegistrationRepository gateway;

	public void initialize(TeacherAgeCheck tac) {
		this.field = tac.field();
		this.fkCamp = tac.fkCamp();
		this.campRole = tac.campRole();
		this.message = tac.message();
	}

	@Override
	public boolean isValid(Object value, ConstraintValidatorContext context) {
		Object birthDate = new BeanWrapperImpl(value).getPropertyValue(field);
		Object campId = new BeanWrapperImpl(value).getPropertyValue(fkCamp);
		Object roleInCamp = new BeanWrapperImpl(value).getPropertyValue(campRole);
		Boolean result = true;
		if (birthDate != null && campId != null) {
			LocalDate bd = (LocalDate) birthDate;
			Integer camp = (Integer) campId;
			EnumCamprole role = (EnumCamprole) roleInCamp;
			result = gateway.checkAgeOfTeacher(bd, camp, role);
			if (!result) {
				context.buildConstraintViolationWithTemplate(message).addPropertyNode(field).addConstraintViolation()
						.disableDefaultConstraintViolation();
			}
		}
		return result;
	}

}
