package com.ejie.m62fb.utils.report;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.rowset.serial.SerialBlob;
import javax.sql.rowset.serial.SerialException;

import net.sf.jasperreports.engine.JasperPrint;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.view.jasperreports.JasperReportsPdfView;

import com.ejie.m62fb.utils.error.UFException;
import com.ejie.m62fb.model.documento.DocumentoAcuerdoReserva;
import com.ejie.m62fb.service.registroVPP.DocumentoAcuerdoReservaService;

public class AcuerdoReservaPDFReportView extends JasperReportsPdfView {
  
  protected JasperPrint fillReport(Map<String, Object> model)
	     throws Exception
	  {
	    Properties headers = new Properties();
	    headers.setProperty("Content-type", "application/pdf");
	   if ((model.get("isInline") == null) || (!((Boolean)model.get("isInline")).booleanValue())) {
	     headers.setProperty("Content-Disposition", "attachment; filename=\"" + model.get("fileName") + ".pdf\"");
	     }
	    setHeaders(headers);
	     
	    return super.fillReport(model);
	 }
	protected void writeToResponse(HttpServletResponse response, ByteArrayOutputStream baos)
			throws IOException{
		Cookie cookie = new Cookie("fileDownload", "true");
		cookie.setPath("/");
		response.addCookie(cookie);
		ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
		HttpSession session = attr.getRequest().getSession();
		grabarPDF(session, baos);
		super.writeToResponse(response, baos); 
	}
	private void grabarPDF(HttpSession session,ByteArrayOutputStream baos){
		DocumentoAcuerdoReserva documento=(DocumentoAcuerdoReserva)session.getAttribute("documentoAcuerdoReserva");
		DocumentoAcuerdoReservaService documentoAcuerdoReservaService=(DocumentoAcuerdoReservaService)session.getAttribute("documentoAcuerdoReservaService");
			try {
				documento.setContenido(new SerialBlob(baos.toByteArray()));
			} catch (SerialException e) {
				throw new UFException(e.getMessage());
			} catch (SQLException e) {

				throw new UFException(e.getMessage());
			}
		documentoAcuerdoReservaService.add(documento);
	}
}