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

import java.time.LocalDate;

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

import de.jottyfan.camporganizer.module.registration.RegistrationRepository;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 *
 * @author jotty
 *
 */
public class AlreadyRegisteredCheckValidator implements ConstraintValidator<AlreadyRegisteredCheck, Object> {

	private String field;
	private String fkCamp;
	private String surname;
	private String birthDate;
	private String message;

	@Autowired
	private RegistrationRepository gateway;

	public void initialize(AlreadyRegisteredCheck arc) {
		this.field = arc.field();
		this.fkCamp = arc.fkCamp();
		this.surname = arc.surname();
		this.birthDate = arc.birthDate();
		this.message = arc.message();
	}

	@Override
	public boolean isValid(Object value, ConstraintValidatorContext context) {
		Object forename = new BeanWrapperImpl(value).getPropertyValue(field);
		Object campId = new BeanWrapperImpl(value).getPropertyValue(fkCamp);
		Object theSurname = new BeanWrapperImpl(value).getPropertyValue(surname);
		Object theBirthDate = new BeanWrapperImpl(value).getPropertyValue(birthDate);
		Boolean found = false;
		if (theBirthDate != null) {
			String fn = (String) forename;
			Integer camp = (Integer) campId;
			String sn = (String) theSurname;
			LocalDate bd = (LocalDate) theBirthDate;
			found = gateway.checkAlreadyRegistered(fn, sn, bd, camp);
			if (found) {
				context.disableDefaultConstraintViolation();
				context.buildConstraintViolationWithTemplate(message).addPropertyNode(fkCamp).addConstraintViolation();
				context.buildConstraintViolationWithTemplate("s.o.").addPropertyNode(field).addConstraintViolation();
				context.buildConstraintViolationWithTemplate("s.o.").addPropertyNode(surname).addConstraintViolation();
				context.buildConstraintViolationWithTemplate("s.o.").addPropertyNode(birthDate).addConstraintViolation();
			}
		}
		return !found;
	}

}
