package sikd.sikd5.ctrl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.Serializable;
import java.util.Properties;

import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.HttpServletResponse;

import sikd.sikd5.sikd5bean.util.PropertiesLoader;

/**
 * @author  : agus
 * @tanggal : Feb 6, 2019
 */
@Named
@SessionScoped
public class DownloadCtrl implements Serializable {
	
	 public void download(String fileName) throws Exception {
	        Properties pr = PropertiesLoader.loadProperties("sikd.properties");
	        String foldernya = pr.getProperty("uploadPath")+File.separator+"sinergi";
	        File file = new File(foldernya+File.separator+fileName);
	        BufferedInputStream inp = null;
	        BufferedOutputStream out = null;
	        FacesContext fcontext = FacesContext.getCurrentInstance();
	        HttpServletResponse response = (HttpServletResponse) fcontext.getExternalContext().getResponse();
	        try {
	            inp = new BufferedInputStream(new FileInputStream(file), 10240);

	            response.reset();
	            response.setContentType("application/octet-stream");
	            response.setHeader("Content-Length", String.valueOf(file.length()));
	            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

	            out = new BufferedOutputStream(response.getOutputStream(), 10240);
	            byte[] buffer = new byte[10240];
	            int length;
	            while ((length = inp.read(buffer)) > 0) {
	                out.write(buffer, 0, length);
	            }
	            out.flush();
	        } finally {
	            if (inp != null) {
	                inp.close();
	            }
	            if (out != null) {
	                out.close();
	            }
	        }
	        fcontext.responseComplete();
	    }

}
