MediumTypeValidator.java

/*
 * Copyright 2026 Global Crop Diversity Trust
 * Licensed under the Apache License, Version 2.0
 * See LICENSE file in project root folder or http://www.apache.org/licenses/LICENSE-2.0
 */

package org.gringlobal.custom.validation.javax;

import java.util.Objects;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.genesys.blocks.util.CurrentApplicationContext;
import org.genesys.blocks.util.TransactionHelper;

import org.gringlobal.model.Materiel;
import org.gringlobal.persistence.MaterielRepository;

public class MediumTypeValidator implements ConstraintValidator<MediumTypeField, Materiel> {

	private String mediumType;

	@Override
	public void initialize(MediumTypeField constraintAnnotation) {
		this.mediumType = constraintAnnotation.value();
	}

	@Override
	public boolean isValid(Materiel value, ConstraintValidatorContext context) {
		if (value == null) {
			return true;
		}
		assert value.getId() != null;
		if (value.getTypeCode() == null) {
			var materielRepository = CurrentApplicationContext.getContext().getBean(MaterielRepository.class);
			var th = CurrentApplicationContext.getContext().getBean(TransactionHelper.class);
			return th.executeInTransaction(true, () ->
				Objects.equals(mediumType, materielRepository.getReferenceById(value.getId()).getTypeCode())
			);
		}
		return Objects.equals(mediumType, value.getTypeCode());
	}
}