
package de.ivu.elect.jee.presentation.dynamicform;

import java.util.ArrayList;
import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;

import de.ivu.elect.jee.faces.FacesComponentUtil;

@FacesValidator(FormDataFacesValidator.VALIDATOR_ID)
public class FormDataFacesValidator implements Validator {

  public static final String VALIDATOR_ID = "formDataFacesValidator";

  private static final String DYNAMIC_VALIDATORS_ATTRIBUTE_NAME = "dynamicValidators";

  public FormDataFacesValidator() {
    super();
  }

  @Override
  public void validate(FacesContext ctx, UIComponent component, Object value) {
    for (Validator validator : getDynamicValidators(component)) {
      validator.validate(ctx, component, value);
    }
  }

  @SuppressWarnings("unchecked")
  private List<Validator> getDynamicValidators(UIComponent component) {
    Object result = FacesComponentUtil.getAttribute(component, DYNAMIC_VALIDATORS_ATTRIBUTE_NAME);

    if (result instanceof List< ? >) {
      return (List<Validator>) result;
    }

    return new ArrayList<>();
  }
}
