/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rjconsultores.ventaboletos.service.impl;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zkoss.util.media.AMedia;

import com.rjconsultores.ventaboletos.dao.FormaPagamentoAgenciaDAO;
import com.rjconsultores.ventaboletos.exception.BusinessException;
import com.rjconsultores.ventaboletos.service.FormaPagamentoAgenciaService;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperRunManager;

/**
 *
 * @author Administrador
 */
@Service("formaPagamentoAgenciaService")
public class FormaPagamentoAgenciaServiceImpl implements FormaPagamentoAgenciaService {

	@Autowired
	private FormaPagamentoAgenciaDAO financeiroDAO;
	@Autowired
	private DataSource dataSource;
	private static final Logger log = LogManager.getLogger(FormaPagamentoAgenciaServiceImpl.class);

	public AMedia gerarInforme(InputStream informe, Map parameters) throws BusinessException {
		Connection conn = null;
		AMedia amedia = null;

		try {
			conn = dataSource.getConnection();

			ResultSet rs = financeiroDAO.executarSQL(conn, parameters);
			JRDataSource jrDataSource = new JRResultSetDataSource(rs);

			Date dataInicio = (Date) parameters.get("dataInicio");
			Date dataFinal = (Date) parameters.get("dataFinal");
			Map<String, Object> args = new HashMap<String, Object>();
			args.put("dataInicio", dataInicio);
			args.put("dataFinal", dataFinal);
			final byte[] buf = JasperRunManager.runReportToPdf(informe, args, jrDataSource);

			final InputStream mediais = new ByteArrayInputStream(buf);

			amedia = new AMedia("financeiro.pdf", "pdf", null, mediais);
		} catch (JRException e) {
			log.error("Erro al generar reporte", e);
			throw new BusinessException("MSG.Error");
		} catch (SQLException e) {
			log.error("Error al obtener una conexcion en el datasource", e);
			throw new BusinessException("MSG.Error");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					log.error("Error al cerrar la conexion", e);
				}
			}
		}

		return amedia;
	}
}
