package de.ivu.elect.presentation.system;

import java.io.Serializable;

import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.ivu.elect.business.konfiguration.entity.ElectKonfigurationWerte;
import de.ivu.elect.business.konfiguration.entity.KonfigurationExtendedLoader;

public class BasisUrlResolver implements Serializable {
  private static final Logger LOG = LoggerFactory.getLogger(BasisUrlResolver.class);

  private static final long serialVersionUID = 1L;

  @Inject
  private transient KonfigurationExtendedLoader konfigurationExtendedLoader;

  public String bestimmeBasisUrl() {
    try {
      String result;
      String basisUrl = konfigurationExtendedLoader.resolveStringValue(ElectKonfigurationWerte.HTTP_BASIS_URL);
      if (StringUtils.isNotBlank(basisUrl)) {
        result = basisUrl;
      } else {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();
        result = request.getRequestURL().substring(0, request.getRequestURL().indexOf(request.getContextPath())) + request.getContextPath();
      }

      if (!result.endsWith("/")) {
        result += "/";
      }


      return result;
    } catch (Exception e) {
      LOG.warn("Fehler beim Bestimmen der Basis-Url: " + e.getMessage(), e);
      return "";
    }
  }
}
