
package de.ivu.elect.presentation.benutzerverwaltung.form;

import java.text.MessageFormat;

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

import de.ivu.elect.business.lokalisierung.control.LokalisierungResourceBundle;


import static org.apache.commons.lang3.StringUtils.isNotBlank;

@FacesValidator(PasswordFormatRegexValidator.VALIDATOR_ID)
public class PasswordFormatRegexValidator extends RegexValidator {

  public static final String VALIDATOR_ID = "passwordFormatRegexValidator";

  public static final String PATTERN_ATTRIBUTE_NAME = "pattern";

  public static final String PATTERN_DESCRIPTION_ATTRIBUTE_NAME = "patternDescription";

  protected static final String NOT_MATCHED_DETAIL_ID = NOT_MATCHED_MESSAGE_ID + "_detail";

  public PasswordFormatRegexValidator() {
    super();
  }

  @Override
  public void validate(FacesContext ctx, UIComponent component, Object value) {
    String pattern = (String) component.getAttributes().get(PATTERN_ATTRIBUTE_NAME);

    setPattern(pattern);

    try {
      super.validate(ctx, component, value);
    } catch (ValidatorException ex) {
      tryReplaceDefaultNotMatchedDetail(ctx, component, ex.getFacesMessage(), pattern);

      throw ex;
    }
  }

  private void tryReplaceDefaultNotMatchedDetail(FacesContext ctx, UIComponent component, FacesMessage facesMessage, String pattern) {
    String currentDetail = facesMessage.getDetail();

    if (isNotBlank(currentDetail) && isNotBlank(pattern)) {
      String patternDescription = (String) component.getAttributes().get(PATTERN_DESCRIPTION_ATTRIBUTE_NAME);

      if (isNotBlank(patternDescription)) {
        String defaultNotMatchedDetail = getMessageFromFacesMessagesBundle(ctx, NOT_MATCHED_DETAIL_ID, getPattern());

        if (currentDetail.equals(defaultNotMatchedDetail)) {
          facesMessage.setDetail(getMessageFromFacesMessagesBundle(ctx, NOT_MATCHED_DETAIL_ID, patternDescription));
        }
      }
    }
  }

  private String getMessageFromFacesMessagesBundle(FacesContext ctx, String key, Object... params) {
    try {
      return MessageFormat.format(LokalisierungResourceBundle.INSTANCE.getString(key), params);
    } catch (Exception ignored) {
    }

    return key;
  }
}
