
package de.ivu.elect.jee.faces;

import java.io.Serializable;
import java.util.Date;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.inject.Inject;

public abstract class AbstractEntityFacesValidator<PK> implements Validator, Serializable {

  protected static final long serialVersionUID = 1L;

  public static final String SUMMARY_KEY = "component.input.NON_UNIQUE";

  public static final String DETAIL_KEY = SUMMARY_KEY + "_detail";

  public static final String ENTITY_PK_ATTRIBUTE_NAME = "pk";

  @Inject
  protected UserLocale userLocale;

  public AbstractEntityFacesValidator() {
    super();
  }

  @Override
  public void validate(FacesContext ctx, UIComponent component, Object value) {
    PK pk = getPk(component);

    if (!isValid(pk, value)) {
      Object valueOutput = value;

      // Für Datumsangaben Uhrzeit nicht mit ausgeben (funktioniert nicht bei Input mit Uhrzeit!)
      if (value instanceof Date) {
        valueOutput = userLocale.formatDate((Date) value);
      }

      throw new ValidatorException(FacesMessageUtil.createErrorMessage(ctx, SUMMARY_KEY, DETAIL_KEY,
          FacesComponentUtil.getLocalizedLabelOrId(component), valueOutput));
    }
  }

  protected abstract boolean isValid(PK pk, Object value);

  @SuppressWarnings("unchecked")
  private PK getPk(UIComponent component) {
    return (PK) FacesComponentUtil.getAttributeFromDynamicFormControlOrNormal(component, ENTITY_PK_ATTRIBUTE_NAME);
  }
}
