package de.ivu.elect.presentation;

import java.io.IOException;

import javax.inject.Inject;
import javax.persistence.EntityNotFoundException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

import de.ivu.elect.business.system.boundary.CacheResetSession;

/**
 * ELECTMUC-2455 allgemeine Lösung für das Problem
 */
public class EntityNotFoundFilter implements Filter {

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

  @Override
  public void init(FilterConfig filterConfig) {
    // nichts zu tun
  }

  @Inject
  private transient CacheResetSession cacheResetSession;

  @Override
  public void doFilter(ServletRequest request, ServletResponse response,
                       FilterChain filterChain) throws IOException, ServletException {
    try {
      filterChain.doFilter(request, response);
    } catch (Exception e) {
      try {
        if (isEntityNotFoundException(e)) {
          LOG.warn("EntityNotFoundException - reset Cache\n" + logMessages(e));
          cacheResetSession.resetCache();
          ((HttpServletResponse) response).sendRedirect(getFullURL((HttpServletRequest) request));
          LOG.warn("EntityNotFoundException - reset Cache - done, redirect sent");
          return;
        }
        if (isRedirectFehler(e)) {
          return; // ignorieren
        }
      } catch (Exception handleException) {
        LOG.warn("Fehler beim Behandeln der Exception: " + handleException.getMessage());
      }
      throw e;
    }
  }

  private boolean isRedirectFehler(Exception e) {
    return e!=null && e.getMessage()!=null && (e.getMessage().contains("UT010019") || e.getMessage().contains("Response already commited"));
  }

  private static String getFullURL(HttpServletRequest request) {
    StringBuilder requestURL = new StringBuilder(request.getRequestURL().toString());
    String queryString = request.getQueryString();

    if (StringUtils.isBlank(queryString)) {
      return requestURL.toString();
    }
    return requestURL.append('?').append(queryString).toString();
  }

  private String logMessages(Throwable e) {
    if (e == null) {
      return "";
    }
    return e.getMessage() + "\n" + logMessages(e.getCause());
  }

  private boolean isEntityNotFoundException(Throwable e) {
    if (e == null) {
      return false;
    }
    if (e instanceof EntityNotFoundException || e.getMessage()!=null && e.getMessage().contains("javax.persistence.EntityNotFoundException")) {
      return true;
    }
    return isEntityNotFoundException(e.getCause());

  }

  @Override
  public void destroy() {
    // nichts zu tun
  }
}
