
package de.ivu.elect.presentation.exchange.action;

import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;

import org.primefaces.model.DefaultStreamedContent;

import de.ivu.elect.business.datei.boundary.DateiExportConversationSelect;
import de.ivu.elect.business.datei.entity.AbstractDateiExport;
import de.ivu.elect.business.datei.entity.DateiExport;
import de.ivu.elect.business.exchange.control.ImportExportStreamCreator;
import de.ivu.elect.jee.faces.FacesMessageUtil;
import de.ivu.elect.jee.faces.download.DownloadAction;
import de.ivu.elect.jee.presentation.security.StartViewResolver;

@Named(DateiExportDownloadAction.COMPONENT_NAME)
public class DateiExportDownloadAction extends AbstractDateiExportAction {

  private static final long serialVersionUID = 1L;

  public static final String COMPONENT_NAME = "dateiExportDownloadAction";

  @Inject
  private transient ImportExportStreamCreator streamCreator;

  @Inject
  private transient DownloadAction downloadAction;

  @Inject
  private transient DateiExportConversationSelect dateiExportConversationSelect;

  @Inject
  private transient StartViewResolver startViewResolver;

  public DateiExportDownloadAction() {
    super();
  }

  @Nullable
  @Override
  public String doIt(DateiExport dateiExport) {
    if (AbstractDateiExport.DUMMY.equals(dateiExport)) { // ELECTMUC-982
      FacesMessageUtil.addErrorMessage("datei.nicht.gefunden");

      return startViewResolver.getStartViewId();
    }

    DefaultStreamedContent defaultStreamedContent = dateiExport.getDatei().getDefaultStreamedContent(streamCreator);

    download(defaultStreamedContent);

    // ELECT-10757 dateiExportConversationSelect.clearEntity();

    return null;
  }

  private void download(DefaultStreamedContent content) {
    downloadAction.download(content);
  }

  @Override
  public boolean isAsyncSupported() {
    return false;
  }

  @Override
  public String getLabelKey() {
    return "datei.export.action.download";
  }

  @Override
  public String getIcon() {
    return appIcons.getIconDownload();
  }
}
