
package de.ivu.elect.presentation.interfaces;

import static java.util.stream.Collectors.joining;
import static org.apache.commons.lang3.StringUtils.isNotBlank;

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

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

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;

  protected AbstractInterfacesStatusTestView() {
    super();
  }

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

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

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

    String localizedMessageOrDefault = getLocalizedMessageOrDefault(cause);

    if (isNotBlank(localizedMessageOrDefault) && !result.contains(localizedMessageOrDefault)) {
      result.add(localizedMessageOrDefault);
    }

    addRawCauses(result, cause.getCause());

    return result;
  }

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

    return cause.getLocalizedMessage();
  }

  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;
  }
}
