
package de.ivu.elect.jee.faces.download;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;

import javax.faces.context.FacesContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DownloadAction implements Serializable {

  private static final Logger LOG = LoggerFactory.getLogger(DownloadAction.class);
  private static final long serialVersionUID = 1L;

  public static final int DOWNLOAD_HTTP_RESPONSE_STATUS = 200;


  /**
   * Diese Methode stammt aus der entsprechenen Download-Primefaces-Komponente, die für die im Projekt verwendeten
   * dynamischen Menüs und Actions nicht verwendet werden kann.
   * 
   * @see org.primefaces.component.filedownload.FileDownloadActionListener.processAction(javax.faces.event.ActionEvent
   *      actionEvent)
   * 
   * @param content
   *          Der Stream, der für den Download bestimmt ist, e.g. eine Datei zum downloaden, see
   *          {@link de.ivu.elect.business.datei.entity.AbstractDatei#getDefaultStreamedContent(ExportKonfiguration exportKonfiguration)}
   */
  public void download(DefaultStreamedContent content) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
    String contentDispositionValue = "attachment";

    try {
      response.setContentType(content.getContentType());
      response.setHeader("Content-Disposition", contentDispositionValue + ";filename=\"" + content.getName() + "\"");
      // WASDE-2161 response.addCookie(new Cookie(Constants.DOWNLOAD_COOKIE, "true"));
      if (content.getContentLength() != null) {
        response.setContentLength(content.getContentLength());
      }

      InputStream inputStream = content.getStream();
      OutputStream outputStream = response.getOutputStream();

      IOUtils.copy(inputStream, outputStream);

      response.setStatus(DOWNLOAD_HTTP_RESPONSE_STATUS);
      response.getOutputStream().flush();
      facesContext.responseComplete();
    } catch (IOException e) {
      LOG.warn("Fehler beim Download: " + e.getMessage(), e);
      throw new RuntimeException(e);
    } finally {
      try {
        content.getStream().close();
      } catch (Exception e) {
        LOG.warn("Fehler beim Schließen: " + e.getMessage());
      }
    }
  }

}
