package mx.gob.jumapacelaya.services;

import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Map;

@Service
public class ReportService {

    @Value("${db.url}")
    private String dbUrl;
    @Value("${db.user}")
    private String dbUser;
    @Value("${db.pass}")
    private String dbPass;

    public byte[] generarReporte(String nombreReporte, Map<String, Object> parametros) throws Exception {

        InputStream logo = getClass().getResourceAsStream("/META-INF/resources/images/LOGO_24'27.png");
        parametros.put("logo", logo);
        InputStream firmaGcia = getClass().getResourceAsStream("/META-INF/resources/images/FirmaGerenteTI.png");
        parametros.put("firmaGcia", firmaGcia);

        InputStream jasperStream = getClass().getResourceAsStream("/META-INF/resources/reportes/" + nombreReporte + ".jasper");
        if (jasperStream == null) {
            throw new IllegalArgumentException("No se encontro el archivo del reporte: " + nombreReporte);
        }

        try (Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPass)) {
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperStream, parametros, conn);
            return JasperExportManager.exportReportToPdf(jasperPrint);
        }
    }
}
