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

import static java.util.Objects.nonNull;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.commons.lang3.StringUtils.trim;

import javax.annotation.Nonnull;

public abstract class AbstractSelectManyStringAutoCompleteProperty extends AbstractSelectManyAutoCompleteProperty<String> {

  private final String unknowOptionLabelSuffixMsgKey;

  private String unknowOptionLabelSuffix;

  public AbstractSelectManyStringAutoCompleteProperty(AbstractAutoCompleteStringOptionsProvider< ? > optionsProvider) {
    this(optionsProvider, null);
  }

  public AbstractSelectManyStringAutoCompleteProperty(AbstractAutoCompleteStringOptionsProvider< ? > optionsProvider, String unknowOptionLabelSuffixMsgKey) {
    super(optionsProvider);

    this.unknowOptionLabelSuffixMsgKey = unknowOptionLabelSuffixMsgKey;
    this.unknowOptionLabelSuffix = null;
  }

  @Override
  public boolean isDropdownEnabled() {
    return hasOptions();
  }

  @Override
  protected boolean isForceOptionSelection() {
    return false;
  }

  @Override
  protected String formatOptionLabel(@Nonnull String option) {
    if (isNotBlank(option)) {
      return trim(option + tryGetUnknowOptionLabelSuffix(option));
    }

    return "";
  }

  private String tryGetUnknowOptionLabelSuffix(String option) {
    if (isForceOptionSelection() || isBlank(option) || getOptions().contains(option)) {
      return "";
    }

    return " " + getUnknowOptionLabelSuffix();
  }

  private String getUnknowOptionLabelSuffix() {
    if (nonNull(unknowOptionLabelSuffix)) {
      return unknowOptionLabelSuffix;
    }

    if (isNotBlank(unknowOptionLabelSuffixMsgKey)) {
      unknowOptionLabelSuffix = getMessage(unknowOptionLabelSuffixMsgKey);
    } else {
      unknowOptionLabelSuffix = "";
    }

    return unknowOptionLabelSuffix;
  }
}
