
package de.ivu.elect.business.konfiguration.control;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class EnumValueNotDeprecatedValidator implements Validator {

  private static final Logger LOG = LoggerFactory.getLogger(EnumValueNotDeprecatedValidator.class);

  private static final String MSG_KEY_VALUE_DEPRECATED = "enum.value.deprecated";

  public EnumValueNotDeprecatedValidator() {
    super();
  }

  @Override
  public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
    if (isValueDeprecated(value)) {
      FacesMessage facesMessage = createErrorMessage(context, MSG_KEY_VALUE_DEPRECATED, value);
      LOG.error("Enum-Wert \"{}\" ist als deprecated markiert, wird aber verwendet", value);

      throw new ValidatorException(facesMessage);
    }
  }

  FacesMessage createErrorMessage(FacesContext context, String msgKey, Object... params) {
    return FacesMessageUtil.createErrorMessage(context, msgKey, msgKey, params);
  }

  public static boolean isValueDeprecated(Object value) {
    if (value instanceof Enum< ? >) {
      try {
        Enum< ? > enumValue = (Enum< ? >) value;
        Class< ? extends Enum> enumClazz = enumValue.getClass();
        Enum< ? >[] enumValues = enumClazz.getEnumConstants();

        if (enumValues != null && enumValues.length > 1) { // ELECT-15090
          Deprecated annotationOrNull = enumClazz.getField(enumValue.name()).getAnnotation(Deprecated.class);

          return annotationOrNull != null;
        }
      } catch (Exception ignored) {
      }
    }

    return false;
  }
}
