
package de.ivu.elect.business.person.entity;

import de.ivu.elect.business.person.entity.PersonendatenProperties.RufnameProperty;
import de.ivu.elect.jee.faces.Messages;

import javax.faces.application.FacesMessage;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import java.util.Objects;
import java.util.regex.Pattern;

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

// ELECTVAPP-1887
public class NlRufnameProperty extends RufnameProperty {

  private static final String RUFNAME_REG_EX = "^\\p{Lu}.+";

  private static final Pattern RUFNAME_PATTERN = Pattern.compile(RUFNAME_REG_EX);

  private static final String PAST_VALIDATED_ATTRIBUTE_NAME_PREFIX = "NlRufnameProperty#PAST_VALIDATED_";

  public NlRufnameProperty(Personendaten personendaten) {
    super(personendaten);

    getValidators().add(createRufnameValidator(getMessages())); // ELECTVAPP-1887
  }

  @Override
  public void setValue(String value) {
    new NlPersonendaten(entity).setVorname(value);
  }

  public static Validator createRufnameValidator(Messages messages) {
    return (facesContext, uiComponent, value) -> {
      if (value != null) {
        String valueOrBlank = trimToEmpty(value.toString());

        if (isNotBlank(valueOrBlank)) { // Nur gesetzte Werte validieren -> für Pflichtfeld required == true verwenden!

          String pastValidatedAttributeName = PAST_VALIDATED_ATTRIBUTE_NAME_PREFIX +  uiComponent.getClientId();

          if (!RUFNAME_PATTERN.matcher(valueOrBlank).matches() && !Objects.equals(value, uiComponent.getAttributes().get(pastValidatedAttributeName))) {
            uiComponent.getAttributes().put(pastValidatedAttributeName, valueOrBlank);

            String errorMessage = messages.getMessageForMessageKey("personendaten.vorname.format.error");

            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_WARN, errorMessage, errorMessage));
          }
        }
      }
    };
  }
}
