package de.ivu.elect.presentation.exchange;

import java.io.Serializable;

import javax.inject.Named;

import org.apache.deltaspike.core.api.scope.ViewAccessScoped;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.ivu.elect.jee.exception.ElectCommonExceptionHandler;
import de.ivu.elect.jee.faces.FacesContextUtil;
import de.ivu.elect.jee.faces.FacesMessageUtil;
import de.ivu.elect.jee.presentation.redirect.Redirect;

/**
 * ELECT-1504
 * IE verhält sich beim Import von Dateien anders, diese Klasse ist der Workaround dafür...
 */
@ViewAccessScoped
@Named(ImportSearchAfterUploadRedirect.COMPONENT)
public class ImportSearchAfterUploadRedirect implements Serializable {

  private static final long serialVersionUID = 1L;

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

  public static final String COMPONENT = "importSearchAfterUploadRedirect";

  private String redirectToViewId;

  private Throwable throwable;

  public void finish() {
    if (throwable != null) {
      handleError(throwable);
    } else {
      String viewId = redirectToViewId;
      redirectToViewId = null; // löschen, damit beim nächsten Upload garantiert weg
      if (viewId == null) {
        FacesContextUtil.redirectToView(FacesContextUtil.getCurrentViewId());
      } else {
        FacesContextUtil.redirectToView(viewId);
      }
    }
  }

  private void handleError(Throwable t) {
    throwable = null;
    ElectCommonExceptionHandler.handleException(t);
  }

  @Redirect
  public String handleError() {
    LOG.info("handleError");
    FacesMessageUtil.addErrorMessage("upload.error.message");
    if (throwable != null) {
      handleError(throwable);
    }
    redirectToViewId = null;
    return FacesContextUtil.getCurrentViewId();
  }

  public String getRedirectToViewId() {
    return redirectToViewId;
  }

  public void setRedirectToViewId(String redirectToViewId) {
    this.redirectToViewId = redirectToViewId;
  }

  public void setThrowable(Throwable throwable) {
    this.throwable = throwable;
  }
}
