
package de.ivu.elect.exchange;

import static java.util.Objects.nonNull;

import de.ivu.elect.business.exchange.control.FileFormat;
import de.ivu.elect.jee.exception.ElectCommonException;

public class ExchangeException extends ElectCommonException {

  private static final long serialVersionUID = 1L;

  public ExchangeException(String messageKey, Object... objects) {
    super(RedirectDestination.ERROR_VIEW, messageKey, objects);
  }

  public static ExchangeException newFileTypeNotSupportedException(FileFormat fileFormat, Iterable< ? extends ExchangeMapper< ? >> mappersSupported) {
    return new ExchangeException("exchange.exception.filetype.not.supported", formatString(fileFormat), formatString(mappersSupported));
  }

  public static ExchangeException newMapperAmbiguousException(FileFormat fileFormat, Iterable< ? extends ExchangeMapper< ? >> mappersAmbiguous) {
    return new ExchangeException("exchange.exception.mapper.ambiguous", formatString(fileFormat), formatString(mappersAmbiguous));
  }

  private static String formatString(Iterable< ? extends ExchangeMapper< ? >> mappers) {
    StringBuilder result = new StringBuilder();

    int maxNumberOfMappersLogged = 3;
    int numberOfMappers = 0;

    for (ExchangeMapper< ? > mapper : mappers) {
      if (numberOfMappers < maxNumberOfMappersLogged) {
        if (numberOfMappers > 0) {
          result.append(", ");
        }

        result.append(mapper.getClass().getSimpleName());
      }

      numberOfMappers++;
    }

    if (numberOfMappers > maxNumberOfMappersLogged) {
      result.append(", ...");
    }

    return result.toString();
  }

  private static String formatString(FileFormat fileFormat) {
    if (nonNull(fileFormat)) {
      return "fileType = " + fileFormat.getFileType() + ", name = " + fileFormat.getName() + "";
    }

    return "";
  }
}
