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

import de.ivu.elect.jee.presentation.dynamicform.AbstractStringProperty;


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

/**
 * ELECT-9905
 */
public class NlZipCodeProperty extends AbstractStringProperty {

  private final AbstractStringProperty zipProperty;

  public NlZipCodeProperty(AbstractStringProperty zipProperty) {
    super();

    this.zipProperty = zipProperty;

    getValidators().add(new NlZipCodeValidator()); // ELECTVAPP-1576
  }

  @Override
  public boolean isRequired() {
    return this.zipProperty.isRequired();
  }

  @Override
  public void setRequired(boolean required) {
    super.setRequired(required);
    this.zipProperty.setRequired(required);
  }

  @Override
  public boolean getDefaultRequired() {
    return false;
  }

  @Override
  public boolean isReadonly() {
    return this.zipProperty.isReadonly();
  }

  @Override
  public void setReadonly(boolean readonly) {
    super.setReadonly(readonly);
    this.zipProperty.setReadonly(readonly);
  }

  @Override
  public int getDefaultMinLength() {
    return this.zipProperty.getDefaultMinLength();
  }

  @Override
  public int getMinLength() {
    return this.zipProperty.getMinLength();
  }

  @Override
  public int getDefaultMaxLength() {
    return this.zipProperty.getDefaultMaxLength();
  }

  @Override
  public int getMaxLength() {
    return this.zipProperty.getMaxLength();
  }

  @Override
  public String getValue() {
    return formatZip(this.zipProperty.getValue());
  }

  @Override
  public void setValue(String value) {
    this.zipProperty.setValue(formatZip(value));
  }

  public static String formatZip(String value) {
    if (isBlank(value)) {
      return value;
    }

    String result = value.toUpperCase();

    if (result.length() == 6) {
      result = result.substring(0, 4) + " " + result.substring(4);
    }

    return result;
  }

  @Override
  public String getDefaultLabel() {
    return this.zipProperty.getDefaultLabel();
  }
}
