
package de.ivu.elect.jee.faces;

import java.io.Serializable;
import java.util.Locale;

import javax.annotation.Nullable;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;

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

@SessionScoped
public class UserLocaleStore implements Serializable {

  private static final long serialVersionUID = 1L;

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

  private Locale locale;

  public UserLocaleStore() {
    super();
  }

  public Locale getLocale() {
    if (locale == null) {
      locale = getDefaultClientLocale();
    }

    if (locale == null) {
      locale = getDefaultServerLocale(); // Fallback
    }

    return locale;
  }

  @Nullable
  protected Locale getDefaultClientLocale() {
    try {
      return FacesContext.getCurrentInstance().getViewRoot().getLocale();
    } catch (Exception ex) {
      LOG.warn("Fehler beim Lesen des Locales: {}", ex.getMessage());
    }

    return null;
  }

  protected Locale getDefaultServerLocale() {
    return Locale.getDefault();
  }

  public void setLocale(Locale locale) {
    this.locale = locale;
  }
}
