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

import de.ivu.elect.business.person.entity.PersonendatenProperties.FamiliennameProperty;
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.isNotBlank;
import static org.apache.commons.lang3.StringUtils.trimToEmpty;

// ELECTVAPP-1887
public class NlFamiliennameProperty extends FamiliennameProperty {

  private static final String FAMILIENNAME_REG_EX = ".*\\p{Lu}.+";

  private static final Pattern FAMILIENNAME_PATTERN = Pattern.compile(FAMILIENNAME_REG_EX);

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

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

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

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

  public static Validator createFamiliennameValidator(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 (!FAMILIENNAME_PATTERN.matcher(valueOrBlank).matches() && !Objects.equals(value, uiComponent.getAttributes().get(pastValidatedAttributeName))) {
            uiComponent.getAttributes().put(pastValidatedAttributeName, valueOrBlank);

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

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