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

import java.util.regex.Pattern;

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

import org.apache.commons.lang3.StringUtils;

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

public class NlZipCodeValidator implements Validator {
  private static final Pattern ZIP_PATTERN = Pattern.compile("\\d\\d\\d\\d ?[a-zA-Z][a-zA-Z]");

  @Override
  public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {

    if (value == null) {
      return;
    }

    String valueAsString  = value.toString().trim();
    if (StringUtils.isBlank(valueAsString)) {
      return;
    }


    if (!isMatches(valueAsString)) {
      throw new ValidatorException(
          FacesMessageUtil.createErrorMessage(context, "nl.zip.format.falsch", "nl.zip.format.falsch", value));
    }

  }

  static boolean isMatches(String valueAsString) {
    return ZIP_PATTERN.matcher(valueAsString).matches();
  }

}
