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

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

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

import de.jottyfan.camporganizer.module.registration.RegistrationRepository;

/**
 *
 * @author jotty
 *
 */
public class UnusedUsernameValidator implements ConstraintValidator<UnusedUsername, Object> {

	private String field;
	private String message;

	@Autowired
	private RegistrationRepository gateway;

	public void initialize(UnusedUsername uu) {
		this.field = uu.field();
		this.message = uu.message();
	}

	@Override
	public boolean isValid(Object value, ConstraintValidatorContext context) {
		Object login = new BeanWrapperImpl(value).getPropertyValue(field);
		Boolean result = gateway.isLoginNotYetInUse((String) login);
		if (!result) {
			context.buildConstraintViolationWithTemplate(message).addPropertyNode(field).addConstraintViolation()
					.disableDefaultConstraintViolation();
		}
		return result;
	}

}
