
package de.ivu.elect.presentation.interfaces;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Nullable;
import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;

import de.ivu.elect.business.konfiguration.entity.KonfigurationExtendedLoader;
import de.ivu.elect.business.konfiguration.entity.MandantKonfigurationWerte;
import de.ivu.elect.business.mandant.entity.Mandant;
import de.ivu.elect.business.security.control.ElectCommonPrincipal;
import de.ivu.elect.jee.faces.Messages;

public abstract class AbstractInterfacesStatusTestView implements Serializable {

  private static final long serialVersionUID = 1L;

  @Inject
  private transient Messages messages;

  @Inject
  private transient ElectCommonPrincipal principal;

  @Inject
  private transient KonfigurationExtendedLoader konfigurationExtendedLoader;

  public AbstractInterfacesStatusTestView() {
    super();
  }

  protected <V extends Enum<?>> V resolveEnumValue(MandantKonfigurationWerte mandantKonfigurationWerte, Class<V> enumClass) {
    return konfigurationExtendedLoader.resolveEnumValue(getMandant(), mandantKonfigurationWerte, enumClass);
  }

  protected String getLocalizedMessageOrDefault(@Nullable Throwable cause) {
    if (cause == null) {
      return "";
    }

    return cause.getLocalizedMessage();
  }

  protected String getRawCausesOrDefault(@Nullable Throwable cause) {
    return addRawCauses(new ArrayList<>(), cause).stream().collect(Collectors.joining(System.lineSeparator()));
  }

  private List<String> addRawCauses(List<String> result, @Nullable Throwable cause) {
    if (cause == null) {
      return result;
    }

    String localizedMessageOrDefault = getLocalizedMessageOrDefault(cause);
    if (StringUtils.isNotBlank(localizedMessageOrDefault) && !result.contains(localizedMessageOrDefault)) {
      result.add(localizedMessageOrDefault);
    }

    addRawCauses(result, cause.getCause());
    return result;
  }

  protected Mandant getMandant() {
    return principal.getMandant();
  }

  protected String getMessage(Enum<?> enumValue) {
    return getMessages().lokalisiere(enumValue);
  }

  protected String getMessage(String msgKey, Object... params) {
    return getMessages().getMessageForMessageKey(msgKey, params);
  }

  private Messages getMessages() {
    return messages;
  }
}
