
package de.ivu.elect.jee.presentation.dynamicform;

import java.util.ArrayList;
import java.util.Collection;
import java.util.function.Consumer;
import java.util.function.Supplier;

import javax.faces.validator.LengthValidator;
import javax.faces.validator.Validator;

public class LambdaStringProperty extends AbstractStringProperty {

  private final boolean defaultRequired;

  private final String defaultValue;

  private final String defaultLabel;

  private final Consumer<String> setter;

  private final Supplier<String> getter;

  private final Integer minLength;

  private final Integer maxLength;

  public LambdaStringProperty(String defaultLabel, boolean defaultRequired, Consumer<String> setter, Supplier<String> getter, Integer minLength, Integer maxLength) {
    this(defaultLabel, null, defaultRequired, setter, getter, minLength, maxLength);
  }

  public LambdaStringProperty(String defaultLabel, String defaultValue, boolean defaultRequired, Consumer<String> setter, Supplier<String> getter, Integer minLength, Integer maxLength) {
    super();

    this.defaultValue = defaultValue;
    this.defaultRequired = defaultRequired;
    this.defaultLabel = defaultLabel;

    this.setter = setter;
    this.getter = getter;

    this.minLength = minLength;
    this.maxLength = maxLength;
  }

  @Override
  public String getDefaultValue() {
    return defaultValue;
  }

  @Override
  public String getValue() {
    return getter.get();
  }

  @Override
  public void setValue(String value) {
    setter.accept(value);

  }

  @Override
  public int getDefaultMaxLength() {
    return maxLength;
  }

  @Override
  public String getDefaultLabel() {
    return defaultLabel;
  }

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

  @Override
  public int getDefaultMinLength() {
    return minLength;
  }

  @Override
  public Collection<Validator> getValidators() {
    Collection<Validator> validators = new ArrayList<>(super.getValidators());

    if (getMinLength() > 0) {
      validators.add(new LengthValidator(getMaxLength(), getMinLength()));
    } else {
      validators.add(new LengthValidator(getMaxLength()));
    }

    return validators;
  }
}
