package de.ivu.elect.presentation.exchange;

import java.io.Serializable;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.deltaspike.core.api.scope.ViewAccessScoped;

import de.ivu.elect.jee.exception.ElectCommonExceptionHandler;
import de.ivu.elect.jee.faces.FacesContextUtil;
import de.ivu.elect.jee.faces.Messages;

/**
 * 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 {

  @Inject
  Messages messages;

  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, messages);
  }

  public String getRedirectToViewId() {
    return redirectToViewId;
  }

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

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