
package de.ivu.elect.presentation.system;

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.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.model.StreamedContent;

/**
 *  on 15.11.2016.
 */
public class FileDownloader implements Serializable {

  private static final long serialVersionUID = 1L;

  public FileDownloader() {
    super();
  }

  public void downloadInline(StreamedContent streamedContent) {
    try {
      HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();

      response.reset();
      response.setHeader("Content-Type", streamedContent.getContentType());
      if (streamedContent.getContentLength() != null) {
        response.setHeader("Content-Length", Integer.toString(streamedContent.getContentLength()));
      }
      if (StringUtils.isBlank(streamedContent.getName())){
        response.setHeader("Content-Disposition", "inline");
      } else {
        response.setHeader("Content-Disposition", "inline; filename=\"" + streamedContent.getName() + "\"");
      }

      try (InputStream is = streamedContent.getStream()) {
        try (OutputStream os = response.getOutputStream()) {
          IOUtils.copy(is, os);
          os.flush();
          FacesContext.getCurrentInstance().responseComplete();
        }
      }
    } catch (IOException e) {
      throw new RuntimeException(e.getMessage(), e);
    }
  }
}
