
package de.ivu.elect.jee.faces;

import java.io.Serializable;
import java.util.ResourceBundle;

import javax.enterprise.context.ApplicationScoped;
import javax.faces.validator.BeanValidator;
import javax.inject.Inject;
import javax.inject.Named;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.ivu.elect.jee.faces.messagehelper.AbstractResourceBundleResolver;

@Named
@ApplicationScoped // ELECT-7845
public class Messages implements Serializable {

  private static final long serialVersionUID = 1L;

  public static final String LOCALIZED_MESSAGE_ONLY_MSG_KEY = BeanValidator.MESSAGE_ID; // msgKey = {0}

  private static final Logger LOG = LoggerFactory.getLogger(Messages.class);

  @Inject
  private transient AbstractResourceBundleResolver resolver;

  public Messages() {
    super();
  }

  public void addInfoMessage(String key, Object... params) {
    FacesMessageUtil.addInfoMessage(key, params);
  }

  public void addWarnMessage(String key, Object... params) {
    FacesMessageUtil.addWarnMessage(key, params);
  }

  public void addErrorMessage(String key, Object... params) {
    FacesMessageUtil.addErrorMessage(key, params);
  }

  public void addThrowableMessageAndLog(String key, Throwable e, Object... params) {
    LOG.warn(e.getMessage(), e);

    FacesMessageUtil.addErrorMessage(key, params);
  }

  public String getMessageForMessageKey(String msgKey, Object... params) {
    return FacesMessageUtil.getResourceText(getResourceBundle(), msgKey, params);
  }

  public boolean isMessageKeyVorhanden(String msgKey) {
    return getResourceBundle().containsKey(msgKey);
  }

  public String lokalisiere(Enum< ? > enumValue) {
    if (enumValue == null) {
      return null;
    }

    return getMessageForMessageKey(FacesMessageUtil.getEnumMessageKey(enumValue));
  }

  public String lokalisiere(Enum< ? > enumValue, Object... params) {
    if (enumValue == null) {
      return null;
    }

    return getMessageForMessageKey(FacesMessageUtil.getEnumMessageKey(enumValue), params);
  }

  public String lokalisiere(Enum< ? > enumValueMain, Enum< ? > enumValueDetail) {
    if (enumValueMain == null) {
      return null;
    }

    return getMessageForMessageKey(FacesMessageUtil.getEnumMessageKey(enumValueMain, enumValueDetail));
  }

  public String lokalisiere(Boolean object) {
    return getMessageForMessageKey("boolean." + object);
  }

  public ResourceBundle getResourceBundle() {
    return resolver.getResourceBundle();
  }
}
