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

import org.springframework.beans.BeanWrapperImpl;

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

/**
 *
 * @author jotty
 *
 */
public class ValidUsernameValidator implements ConstraintValidator<ValidUsername, Object> {

	private String field;
	private String message;
	private String require;

	public void initialize(ValidUsername vu) {
		this.field = vu.field();
		this.message = vu.message();
		this.require = vu.require();
	}

	@Override
	public boolean isValid(Object value, ConstraintValidatorContext context) {
		Boolean forceCheck = (Boolean) new BeanWrapperImpl(value).getPropertyValue(require);
		Boolean result = null;
		if (forceCheck != null && forceCheck) {
			Object login = new BeanWrapperImpl(value).getPropertyValue(field);
			String loginString = String.valueOf(login);
			result = login != null && !loginString.isBlank() && !loginString.contains(" ");
			if (!result) {
				context.buildConstraintViolationWithTemplate(message).addPropertyNode(field).addConstraintViolation()
						.disableDefaultConstraintViolation();
			}
		} else {
			result = true;
		}
		return result;
	}

}
