package tvark.servlet;

import java.io.IOException;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tvark.beans.ResultsBean;

public class DownloadServlet extends HttpServlet {

	private static final long serialVersionUID = 5848125646244268750L;
	
	private static final String FILE_NAME = "tvark.zip";

	@Override
	protected void doGet(HttpServletRequest pReq, HttpServletResponse pResp)
			throws ServletException, IOException {
		
		FacesContext ctx = FacesContext.getCurrentInstance();
		ExpressionFactory f = ctx.getApplication().getExpressionFactory();
		ELContext elctx = ctx.getELContext();
		ResultsBean resultsBean = (ResultsBean) f.createValueExpression(elctx, "#{resultsBean}", ResultsBean.class).getValue(elctx);
		byte[] zip = resultsBean.getAsZip();
		
		pResp.setContentLength(zip.length);
		pResp.addHeader("Content-Disposition", "attachment; filename=" + FILE_NAME);
		pResp.getOutputStream().write(zip);
	}

}
