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

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

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

public class ExchangeListConverter {

  private static final String DEFAULT_DELIMITER = ",";

  private final String delimiter;

  private final ExchangeTypeConverter itemTypeConverter;

  public ExchangeListConverter(ExchangeTypeConverter itemTypeConverter) {
    this(DEFAULT_DELIMITER, itemTypeConverter);
  }

  public ExchangeListConverter(String delimiter, ExchangeTypeConverter itemTypeConverter) {
    super();

    this.delimiter = delimiter;

    this.itemTypeConverter = itemTypeConverter;
  }

  /**
   * copied from org.jsefa.common.converter modified by WAA
   */
  public Object fromString(String value) {
    List<Object> result = new ArrayList<>();

    if (isBlank(value)) {
      return result;
    }

    int lastIndex = 0;
    int index = value.indexOf(this.delimiter);

    while (index != -1) {
      result.add(this.itemTypeConverter.fromString(value.substring(lastIndex, index)));

      lastIndex = index + this.delimiter.length();
      index = value.indexOf(this.delimiter, lastIndex);
    }

    result.add(this.itemTypeConverter.fromString(value.substring(lastIndex)));

    return result;
  }

  /**
   * copied from org.jsefa.common.converter modified by WAA
   */
  public String toString(Object value) {
    StringBuilder result = new StringBuilder();

    Collection list = (Collection) value;

    int listSize = list.size();
    int itemIndex = 0;

    for (Object item : list) {
      result.append(this.itemTypeConverter.toString(item));

      if (++itemIndex < listSize) {
        result.append(this.delimiter);
      }
    }

    return result.toString();
  }
}
