package de.ivu.elect.business.exchange.boundary;

import java.util.Collection;
import java.util.List;

import javax.faces.convert.ConverterException;

import static java.util.Arrays.asList;
import static java.util.Collections.unmodifiableList;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.commons.lang3.StringUtils.normalizeSpace;

public class ExchangeBooleanConverter implements ExchangeTypeConverter {

  public static final List<String> DEFAULT_TRUE_ALIASES = asList("1", "true", "wahr","yes","ja","on","an","j");

  public static final List<String> DEFAULT_FALSE_ALIASES = asList("0","false","falsch","no","nein","off","aus","n");

  private final List<String> trueAliases;

  private final List<String> falseAliases;

  public ExchangeBooleanConverter() {
    this(DEFAULT_TRUE_ALIASES, DEFAULT_FALSE_ALIASES);
  }

  public ExchangeBooleanConverter(List<String> trueAliases, List<String> falseAliases) {
    super();

    this.trueAliases = trueAliases;
    this.falseAliases = falseAliases;
  }
  
  

  protected List<String> getTrueAliases() {
    return unmodifiableList(trueAliases);
  }

  protected List<String> getFalseAliases() {
    return unmodifiableList(falseAliases);
  }

  @Override
  public Boolean fromString(String value) {
    if (isNotBlank(value)) {
      String valueNormalized = normalizeSpace(value);

      if (matchesAlias(getTrueAliases(), valueNormalized)) {
        return Boolean.TRUE;
      }

      if (matchesAlias(getFalseAliases(), valueNormalized)) {
        return Boolean.FALSE;
      }

      throw new ConverterException("Unknown boolean value: " + value);
    }

    return Boolean.FALSE;
  }

  @Override
  public String toString(Object value) {
    if (value == null) {
      return "";
    }

    if (((Boolean) value).booleanValue()) {
      return getTrueAliases().get(0);
    }

    return getFalseAliases().get(0);
  }

  private boolean matchesAlias(Collection<String> aliases, String value) {
    for (String alias : aliases) {
      if (alias.equalsIgnoreCase(value)) {
        return true;
      }
    }

    return false;
  }
}
